Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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

The map error means a value you expected to be an array is undefined. Initialise state, validate the API shape and keep an honest loading branch.

~5 min readReact
#react#javascript#state#api
Bold white headline reading UNDEFINED MAP with a React list crate showing an empty amber array slot beside a cyan data block.

Introduction & Quick Summary

The browser console says only this, with a minified stack you cannot read:

code
Uncaught TypeError: Cannot read properties of undefined (reading 'map') at BlogList (chunk-4f9a1c.js:1:8421)

Quick answer: something you expected to be an array is undefined. Give it a default and stop trusting the shape:

tsx
export function BlogList({ posts }: { posts?: Post[] }) { if (!posts?.length) return <p>No posts yet.</p>; return ( <ul> {posts.map((p) => ( <li key={p.slug}>{p.title}</li> ))} </ul> ); }

The message is React's, but the bug is ordinary JavaScript: x.map is evaluated before the call, and x is undefined. In React the usual suspects are narrow and repeatable — state initialised as null, a prop that was never passed, an API response whose shape is not what the component assumes, and a useEffect that renders once before the fetch resolves. Each has a different right fix, so identify which one you have before adding ?. everywhere.

Core Mechanics, Signatures & Reproducible Setup

Array.prototype.map exists only on arrays. The error text names the reason undefined appeared, not the property you called, which is why "reading 'map'" is a symptom rather than a diagnosis. Reproduce it in one file:

tsx
import { useEffect, useState } from "react"; type Post = { slug: string; title: string }; export function Broken() { const [posts, setPosts] = useState<Post[]>(); // undefined, not [] useEffect(() => { fetch("/api/posts") .then((r) => r.json()) .then((d) => setPosts(d.items)); // shape assumed }, []); return <ul>{posts.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>; }

Two defects are stacked here. useState<Post[]>() declares the state type but the value starts as undefined, so the first render throws before the effect runs. And d.items is an assumption; when the API returns { data: { items } } the second render throws instead.

Calling .map on something that is not an array produces related messages:

ValueMessage you seeReal shape
undefinedCannot read properties of undefined (reading 'map')missing or not yet loaded
nullCannot read properties of null (reading 'map')explicitly empty state
{}x.map is not a functionobject where array expected
"abc"x.map is not a functionstring
NodeListx.map is not a functionArray.from(x) first

Key Comparison Table

Where the undefined comes from, and the fix that belongs to each cause:

CauseTypical codeCorrect fix
State has no initial valueuseState<Post[]>()useState<Post[]>([])
Prop never passed<List /> with optional proprequired prop or default parameter
API shape mismatchsetPosts(res.data) when it is an enveloperead the real field, type it
Effect has not run yetfirst render before fetchloading state, not a guard
Context defaultcreateContext(null)default to an empty array
Conditional resetsetPosts(data.error ? undefined : data)keep the type honest

Guard styles, ranked by how much they hide:

StyleKeeps the error visibleHandles nested dataGood for
useState<Post[]>([])yesnostate with an array type
Array.isArray(x)yesnodata from JSON.parse
x?.map(...)no, renders nothingyesgenuinely optional lists
(x ?? []).map(...)noyesone-off local guards
Validate at the boundaryyes, with a clear erroryesAPIs, fetch, storage

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Initialise state to the type you declared

useState<Post[]>() is legal TypeScript that produces undefined. The generic says what the value will be later, not what it is now.

tsx
const [posts, setPosts] = useState<Post[]>([]); const [selected, setSelected] = useState<Post | null>(null);

The same trap appears with useRef<Post[]>(), whose .current starts as undefined, and with let items: Post[]; inside a component body. Whenever a value is read during render, it needs a value during render.

2. Props without defaults fail only where they are used

tsx
type Props = { posts?: Post[] }; export function List({ posts = [] }: Props) { return <ul>{posts.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>; }

A default parameter is cheaper than a guard at every call site, and it documents the intent: "this component works with no rows". If a list is required, keep the prop required and let the parent fail at compile time instead. The middle ground — optional prop, no default, posts.map in the body — is the one that reaches production.

3. API envelopes are the most common real cause

tsx
type Envelope<T> = { data: T; meta: { page: number } }; async function loadPosts(): Promise<Post[]> { const res = await fetch("/api/posts"); if (!res.ok) throw new Error(`HTTP ${res.status}`); const body: unknown = await res.json(); const env = body as Envelope<{ posts: Post[] }>; return Array.isArray(env?.data?.posts) ? env.data.posts : []; }

Axios adds a layer: const res = await axios.get(...) puts the payload in res.data, so res.data.posts is correct and res.items is undefined. Supabase returns { data, error }, and data is null on error, not []. Print the real body once with the JSON formatter instead of guessing, and turn an exported CSV or a pasted payload into JSON with the CSV to JSON converter when the data comes from a spreadsheet.

4. Nested access and the loading state

posts.map is one level deep; post.comments.map inside the row can throw on the second item after the list rendered fine.

tsx
{posts.map((p) => ( <article key={p.slug}> <h2>{p.title}</h2> {(p.comments ?? []).map((c) => ( <p key={c.id}>{c.body}</p> ))} </article> ))}

For the list itself, prefer an explicit loading branch over an empty-array default when the difference matters to the user:

tsx
if (status === "loading") return <Skeleton rows={3} />; if (status === "error") return <Retry onRetry={reload} />; if (posts.length === 0) return <EmptyState />;

That reads better than a list that flickers "No posts yet" for 300 ms on every navigation.

5. Production stacks, error boundaries and query libraries

In a minified build the stack points into a chunk. Upload source maps and the same error names the component and line. Until then, an error boundary converts the white screen into a message you can act on:

tsx
class Boundary extends React.Component<{ children: React.ReactNode }, { error?: Error }> { state: { error?: Error } = {}; static getDerivedStateFromError(error: Error) { return { error }; } render() { if (this.state.error) return <pre>{this.state.error.message}</pre>; return this.props.children; } }

With TanStack Query the equivalent fix is const { data = [] } = useQuery(...), or destructuring data only when isSuccess is true. Note that query.data is undefined until the first success — the library is telling you the truth, and a data = [] default is the intended contract.

6. .map on the wrong thing entirely

Three variants look like the same bug and are not:

  • Object.values(record).map(...) when record is an array already — harmless, but the types are wrong somewhere.
  • document.querySelectorAll(...).map(...) — a NodeList has forEach but no map; use Array.from.
  • new Map() shadowing Array.prototype.map: a local variable named map or a state setter named map produces "is not a function" at the call site.

Common Compilation/Runtime Mistakes & Version Gotchas

Silencing with as. (posts as Post[]).map(...) compiles and crashes exactly as before. A type assertion removes the warning, not the undefined.

Defaulting to [] so the error disappears. This is correct for state, but it hides a broken API contract. Validate once at the boundary and keep the rest of the app honest.

Optional chaining on the result. posts?.map(...) renders nothing at all, with no message, during the exact render where the user needed feedback. Pair it with a fallback.

Ignoring cleanup and races. Two overlapping requests can resolve out of order, so the second render may set undefined from a stale response. Use an AbortController or an ignore flag:

tsx
useEffect(() => { let cancelled = false; load().then((rows) => { if (!cancelled) setPosts(rows); }); return () => { cancelled = true; }; }, []);

Version notes. React 18 added Strict Mode double-invocation in development, which surfaces effect bugs that used to stay hidden. React 19 changed error reporting for uncaught render errors and added use() for promises, which removes the "render before data" window in components that use it. React 19 also stopped swallowing some errors that previously logged silently, so .map crashes in event handlers now reach the console more reliably than they used to.

Reference material: Rendering lists and Conditional rendering.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.