A React component crashes calling .map on undefined
TypeError: 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.
Fix it fast
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);2Match what you see, then jump to its fix
- 1
The 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
Array.isArray(items) is false and the logged value is an object such as { data: [...] }The response is an object, not the arrayFix - 3
The error says 'reading map' on a prop like user.orders, only for some recordsA prop or nested property can legitimately be missingFix
- 1
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 startConfirmed by react.dev
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 3002Fix
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
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 startConfirmed by developer.mozilla.org
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fixWeb apps
Can't resolve '../axios' in a React project
Module not found: Error: Can't resolve '../axios'
A path that starts with ./ or ../ is a file path, not the axios package.
3 causes, each with a fixWeb apps
Axios returns 401 from a React app but the login works elsewhere
Error: Request failed with status code 401
A 401 means the server received the request without valid credentials.
3 causes, each with a fixWeb apps
An axios call never finishes when the API server stops answering
code: 'ECONNABORTED'
Axios has no timeout unless you give it one: the default is 0, which means wait forever.
3 causes, each with a fix