JavaScriptReact

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

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

In short: Your code used a value before it existed, usually data that hasn't loaded yet or an API response with a different shape.

Why it happens

On first render, fetched data is still undefined. Or the API returns { items: [...] } while the code expects an array, or returns an error object instead of data. AI-generated code often assumes the happy path.

How to fix it

  1. Log the actual value right before the failing line and compare with what the code expects.
  2. Initialise state with the right empty shape: useState<Item[]>([]).
  3. Guard while loading: if (!data) return <Spinner />, or use optional chaining data?.items ?? [].
  4. Check the API response shape and error handling: test res.ok before using JSON.
  5. Add TypeScript types for the response so mismatches show up in the editor.
Don't: Don't sprinkle ?. everywhere without understanding why the value is missing. That hides real API errors.

Copy-paste fix prompt

3 · The fix promptPaste into Cursor, Claude Code, Codex, Lovable, Bolt, Replit or v0
I'm getting this error in my app:

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

[Paste the full error, stack trace, and the file it points to here]

Likely cause: Your code used a value before it existed, usually data that hasn't loaded yet or an API response with a different shape.

Task: Find where this value comes from, show me its actual shape vs. the expected shape, and add proper loading, empty, and error states rather than blanket optional chaining.

Rules:
- First explain the root cause in 2 sentences and list the files you'll change.
- Make the smallest change that fixes it. Don't refactor unrelated code.
- Don't disable security or checks (RLS, auth, signature verification, type checking, CORS allow-all) to make the error disappear.
- Never print or hard-code secret keys.
- Finish by telling me exactly how to verify the fix.

Common with: Cursor, Lovable, Bolt, v0. Last reviewed 2026-11-13.

Related fixes

← All fixes · Still stuck? Use the diagnose-first prompt