ErrorBellFree

Error library / this error

How to fix it

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

What it means

Your code called .map() on a value that is undefined at that moment. It is almost always data that has not arrived yet, or arrived in a different shape than expected.

Common causes

  • A list in state or props has no initial value, so the first render sees undefined.
  • An API response is shaped differently than you assumed, for example { data: [...] } instead of [...].
  • A parent component did not pass the prop, or passed it under another name.

How to fix it

1. Give the value a safe default

An empty array renders an empty list instead of crashing.

// before
const [users, setUsers] = useState();
users.map(renderUser);

// after
const [users, setUsers] = useState([]);
users.map(renderUser);

2. Guard at the point of use

Useful when the value comes from a prop you do not control.

(items ?? []).map(renderItem)

3. Check what the API really returns

Log the response once. If the list lives under a key, read it from there.

const body = await res.json();
setUsers(body.users ?? []);

Catch it the moment it happens

ErrorBell shows a dot on the page when this error occurs and takes you to the failing line, so you do not have to hunt through the console. Add it to Chrome, it is free.

Related errors