Scaleup Infotech
Scaleup Infotech.
Back to Blog
Bug Fixes7 min read

Fix 'Cannot read properties of undefined (reading map)' in React

Scaleup Infotech

Scaleup Infotech

Software & Marketing Agency

May 14, 2026
Fix 'Cannot read properties of undefined (reading map)' in React
ReactJavaScriptAPI

You fetch a list from an API and render it with .map(). It crashes instantly — because on the first render, before the fetch resolves, your state is still undefined. This is the most common runtime error in React apps.

The Error

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

Why This Happens

React renders before your async data arrives. If you initialize state as undefined (or it is a nested property that does not exist yet), calling .map() on it throws.

Fix 1: Initialize State as an Empty Array

jsx
// ❌ undefined on first render
const [users, setUsers] = useState();

// ✅ Always an array — .map() is always safe
const [users, setUsers] = useState([]);

Fix 2: Optional Chaining + Nullish Fallback

When the data is nested or comes from props you do not control, guard the access:

jsx
{(data?.users ?? []).map((u) => (
  <li key={u.id}>{u.name}</li>
))}

Fix 3: Render a Loading / Empty State

The most user-friendly fix — handle the three real states explicitly:

jsx
if (loading) return <Spinner />;
if (!users?.length) return <p>No users found.</p>;

return (
  <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
);

Prevention

In TypeScript, type the state as User[] (not User[] | undefined) and initialize with []. The compiler then stops you from ever rendering an undefined list.

Share this article:

Keep Reading

Ready to implement these ideas?

Work With Scaleup Infotech