Why does array.map() return undefined when array exists in console.log?
Based on your description, this sounds like a JavaScript/React issue where you're trying to .map() over data fetched from Sanity. The problem where you can console.log an array but get undefined when mapping usually happens due to one of these reasons:
1. Async timing issue - most common cause
If you're fetching data from Sanity, the data might not be loaded yet when your component first renders. Your .map() is running before the data arrives:
// ❌ Problem: data might be undefined initially
const MyComponent = () => {
const [data, setData] = useState();
useEffect(() => {
fetchFromSanity().then(setData);
}, []);
return data.map(item => <div>{item.title}</div>); // undefined!
}
// ✅ Solution: Add a conditional check
return data?.map(item => <div>{item.title}</div>) || <div>Loading...</div>;2. GROQ query returns an object, not an array
When you fetch a single document with GROQ, you get an object. If that object contains an array field, you need to access it:
// ❌ If your query is: *[_type == "page"][0]
// You get: { title: "My Page", items: [...] }
data.map() // undefined - data is an object!
// ✅ Solution: Access the array property
data.items?.map(item => ...)3. The .map() itself returns undefined
Make sure your .map() callback actually returns something:
// ❌ No return statement
data.map(item => {
<div>{item.title}</div>
})
// ✅ Implicit return with parentheses
data.map(item => (
<div>{item.title}</div>
))
// ✅ Explicit return
data.map(item => {
return <div>{item.title}</div>
})Quick debugging checklist:
- Check what you're actually getting:
console.log('type:', typeof data, 'value:', data) - Add optional chaining:
data?.map(...) - Verify your GROQ query returns an array (use the Vision plugin in Studio to test queries)
- Make sure your map callback returns JSX
If you're using Next.js with server components, remember that you can fetch Sanity data directly without useState/useEffect, which eliminates the async timing issue entirely. Check out the next-sanity documentation for examples.
Show original thread11 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.