Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

A React component crashes calling .map on undefined

ErrorTypeError: Cannot read properties of undefined (reading 'map')

Short answer

The value you call .map on is undefined or null when React renders. Usually the data has not arrived yet, because state starts empty and the fetch finishes later, or the API response has a different shape than the code assumes. Start state as an empty array, or guard the value before mapping.

  • Applies to React 19, Node.js 22, Chrome 130
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Log the value right before the map call, and the type of it. Undefined on the first render points to timing; a wrong object points to the data shape.

    console.log('items:', typeof items, Array.isArray(items), items);
  2. 2Match what you see, then jump to its fix

    1. 1The error is on the first render; the page works if you remove the map and add it back with hot reloadState starts as undefined or null, and data arrives laterFix
    2. 2Array.isArray(items) is false and the logged value is an object such as { data: [...] }The response is an object, not the arrayFix
    3. 3The error says 'reading map' on a prop like user.orders, only for some recordsA prop or nested property can legitimately be missingFix

What does the error look like?

  • TypeError: Cannot read properties of undefined (reading 'map')
  • TypeError: Cannot read properties of null (reading 'map')
  • TypeError: undefined is not an object (evaluating 'items.map')

Cause 1 of 3

State starts as undefined or null, and data arrives later

1Check

React renders once with the initial state before an effect runs. useState() with no argument gives undefined.

grep -n "useState()" -r src/

2Fix

Give the state an empty array as its initial value, so the first render maps over nothing. React's own fetch example also uses an initial value and shows a fallback until the data arrives.

const [items, setItems] = useState([]);

useEffect(() => {
  let ignore = false;
  fetch("/api/items")
    .then(r => r.json())
    .then(data => { if (!ignore) setItems(data); });
  return () => { ignore = true; };
}, []);

return <ul>{items.map(i => <li key={i.id}>{i.name}</li>)}</ul>;

3Verify

Reload the page. The list renders empty first, then fills in, with no error in the console.

npm start

Confirmed by react.dev

Did this fix it?

Cause 2 of 3

The response is an object, not the array

1Check

Many APIs wrap the list in a field. Print the parsed JSON and see where the array sits.

curl -s https://example.com/api/items | head -c 300

2Fix

Set state from the field that holds the array, and fall back to an empty array if it is missing.

.then(body => setItems(body.items ?? []));

3Verify

Array.isArray(items) logs true after the data loads.

console.log(Array.isArray(items));

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 3

A prop or nested property can legitimately be missing

1Check

Some records do not have the field. MDN lists a property that is not initialized and an API response missing the expected array as common sources.

console.log(user.orders);

2Fix

Use optional chaining with a default, so a missing value renders as an empty list. This hides bad data, so use it only where a missing list is allowed.

{(user.orders ?? []).map(o => <OrderRow key={o.id} order={o} />)}

3Verify

Open a record that has no orders. The component renders and the console is clean.

npm start

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Initialise list state with [] and object state with a real shape, never with no value.
  • Parse and check API responses in one place so components receive the shape they expect.
  • Show a loading state until the data has arrived.
  • Type the data (TypeScript) so a possibly undefined list is flagged before it runs.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.