Sanity fetch returns undefined: "item is not defined" error in React
I can see the issue in your code! You have a syntax error in your useEffect hook. The backticks () are in the wrong place - they should be wrapping the GROQ query string, not the entire sanityClient.fetch()` call.
Here's the corrected version:
useEffect(() => {
sanityClient.fetch(
`*[_type == "item"]{
title,
slug,
mainImage,
}`
)
.then((data) => setItemData(data))
.catch(console.error);
}, []); // Don't forget the dependency array!Key fixes:
- Backticks placement: Move the backticks to wrap only the GROQ query string (the part inside
fetch()), not the entire function call - Dependency array: Add an empty array
[]as the second argument touseEffect- without this, your fetch will run on every render, causing an infinite loop!
Additional tips:
- Make sure you've initialized
sanityClientproperly at the top of your file (usually imported from aclient.jsfile) - Ensure
itemDatais initialized as an empty array:const [itemData, setItemData] = useState([]) - When mapping over the data, you'd do something like:
{itemData && itemData.map((item) => ( <div key={item._id}> <h2>{item.title}</h2> </div> ))}
The "item is not defined" error you're seeing is likely because the fetch isn't working due to the syntax error, so itemData remains empty or undefined. Once you fix the backticks and add the dependency array, your data should load properly and you'll be able to access item.title when mapping over the results.
Show original thread15 replies
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.