JavaScript & React Top React Error

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

Error Message
TypeError: Cannot read properties of undefined (reading 'map') TypeError: items.map is not a function
Quick Fix
{(items || []).map(item => <Card key={item.id} data={item} />)}

Why Does This Happen?

React renders the component before API data arrives. On the first render, your state variable is undefined (not yet an array), so calling .map() on it throws a runtime TypeError.

Step-by-Step Solution

1
Fix 1: Initialize state as an empty array
Set the default value of useState to [] instead of leaving it undefined:
Terminal / Code
// BUG:
const [users, setUsers] = useState();

// FIX:
const [users, setUsers] = useState([]);
An empty array .map() simply returns [] — no crash.
2
Fix 2: Optional chaining (?.)
Safely returns undefined instead of throwing an error:
Terminal / Code
{users?.map(user => (
  <li key={user.id}>{user.name}</li>
))}
Supported in all modern JavaScript and TypeScript environments.
3
Fix 3: Show a loading state
Render a spinner until data arrives:
Terminal / Code
if (loading) return <div>Loading...</div>;
if (!users?.length) return <div>No data found.</div>;
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
Best practice for production React apps.

Common Mistakes to Avoid

Assuming fetch() data is available synchronously on the first render.
Not checking that the API response is actually an array (it might be { data: [...] }).

Frequently Asked Questions

What if it says 'items.map is not a function'?
items exists but is an Object {} or a string — not an Array. Check with console.log(items) or Array.isArray(items).

Learn to Write Code That Doesn't Break

DoxaTech Hub's 10-month programme teaches you Git internals, Linux systems, C, Python, SQL, Docker, and React from first principles — so you spend less time fixing errors and more time shipping.

Start Learning →