Tips for fetching data with Sanity v3 in a React project
6 replies
Last updated: Jun 13, 2023
AI Update
Congrats on upgrading to v3! The good news is that in Sanity v3, you still use @sanity/client to fetch data, but you'll import createClient instead of the old sanityClient export.
Installation
First, install the client library:
npm install @sanity/clientCreating the Client
In v3, you use createClient from @sanity/client:
import { createClient } from '@sanity/client'
export const client = createClient({
projectId: 'your-project-id', // find this in sanity.json or your Studio
dataset: 'production', // or your dataset name
useCdn: true, // set to false if you need fresh data
apiVersion: '2023-05-03', // use current date (YYYY-MM-DD) to target the latest API version
})Fetching Data
Once you have your client configured, you can fetch data using GROQ queries:
import { client } from './client' // wherever you created your client
// In your React component
function MyComponent() {
const [data, setData] = React.useState(null)
React.useEffect(() => {
client.fetch('*[_type == "post"]').then((posts) => {
setData(posts)
})
}, [])
if (!data) return <div>Loading...</div>
return (
<div>
{data.map((post) => (
<div key={post._id}>{post.title}</div>
))}
</div>
)
}Key Differences from v2
- Import
createClientinstead of the default export - The
apiVersionparameter is now required (use a current date in YYYY-MM-DD format) - The client instance works the same way for
.fetch(),.create(),.patch(), etc.
Additional Resources
- Check out the official JavaScript Client on GitHub for full documentation
- The GROQ query cheat sheet is super helpful for writing queries
- For handling images, look into @sanity/image-url
- For rendering rich text (Portable Text), check out @portabletext/react
The React single-page application guide might also be helpful, though it may reference some patterns you can adapt for vanilla React with React Router.
Hope this gets you up and running! 🚀
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.