My app crashes with TypeError: Cannot read properties of undefined (reading 'map'). What does it mean and what is a systematic way to fix it?
DEV3 Developer Forum
How do I debug 'TypeError: Cannot read properties of undefined (reading ...)' in JavaScript?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
It means you wrote something.prop where something is undefined (or null). The word in parentheses is the property you tried to read, which tells you what to look for: reading 'map' means x.map(...) where x is undefined.
Step 1: find which value
Read the stack trace top line (file and line). Log the object just before:
console.log({ items });
or set a breakpoint in DevTools.
Step 2: understand why it is undefined
Typical causes:
- Async data not loaded yet: React state starts as
undefined, the first render runs before the fetch finishes. - Wrong shape: API returns
{ data: { items } }but you readres.items. - Typo or case difference:
user.Namevsuser.name. - Missing return: a function without
returnyieldsundefined. - Array index out of range:
arr[5].name. thislost in callbacks (see thethisrules).- Environment: a variable not set,
JSON.parseof something else.
Step 3: fix at the right place
// default the state
const [items, setItems] = useState([]);
// guard rendering
{items?.map((i) => <Row key={i.id} {...i} />)}
// default while destructuring
const { items = [] } = response ?? {};
Also render a loading state explicitly instead of hiding bugs with ?. everywhere.
Prevent it
- TypeScript with
strictflags these at compile time. - Validate API responses with a schema.
- Use optional chaining only where undefined is a legitimate state.
Pitfall: a try/catch that swallows the error and continues leaves your app in a half-broken state. Fix the cause.
If the data comes from JSON, the JSON formatter helps confirm the real shape.
0