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
- Log the actual value right before the failing line and compare with what the code expects.
- Initialise state with the right empty shape:
useState<Item[]>([]). - Guard while loading:
if (!data) return <Spinner />, or use optional chainingdata?.items ?? []. - Check the API response shape and error handling: test
res.okbefore using JSON. - Add TypeScript types for the response so mismatches show up in the editor.
Copy-paste fix prompt
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.