Why does array.map() return undefined when array exists in console.log?

11 repliesLast updated: Nov 29, 2025

how can I map over an array? I'm getting undefined when trying to use it. i can console log and see the array but when i try and map its returning undefined ?
AI Update

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:

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 thread
11 replies

Was this answer helpful?

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.

Related contributions