ReactError Fix2026 Updated

React Cannot Read Properties of Undefined Reading 'map'— Fixed [2026]

Also covers: map is not a function · undefined before API loads · optional chaining

January 20265 min readReact 18 · Next.js

⚡ Most Common Fix — Initialize as Empty Array

component.jsx
// ❌ WRONG — undefined on first render before API responds
const [users, setUsers] = useState()
users.map(u => ...)  // TypeError!

// ✅ CORRECT — empty array = safe to map, renders nothing
const [users, setUsers] = useState([])
users.map(u => ...)  // works, renders nothing until data arrives

Why Does This Error Happen?

Error
TypeError: Cannot read properties of undefined (reading 'map')
    at UserList (UserList.jsx:8:12)

# or:
TypeError: data.map is not a function

JavaScript's .map() method only exists on arrays. When called on undefined, null, or any non-array value, it throws. In React, this happens most often when data is still loading or was not passed as a prop.

1

Initialize State as Empty Array

The standard fix — safe default value
1 min
components/UserList.jsx
import { useState, useEffect } from 'react'

export default function UserList() {
  // ✅ Always initialize array state as [] not undefined
  const [users, setUsers]   = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/users')
      .then(r => r.json())
      .then(data => {
        setUsers(data)      // replace [] with real data
        setLoading(false)
      })
  }, [])

  if (loading) return <p>Loading users...</p>

  // Safe to map — worst case is an empty array
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}
2

Guard With Loading State Before Mapping

Show skeleton while data loads
2 min
components/ProductGrid.jsx
export default function ProductGrid({ products, loading }) {
  // ✅ Explicit loading guard
  if (loading) {
    return (
      <div className="grid grid-cols-3 gap-4">
        {[...Array(6)].map((_, i) => (
          <div key={i} className="h-32 bg-gray-100 animate-pulse rounded-xl" />
        ))}
      </div>
    )
  }

  // ✅ Null/empty guard
  if (!products || products.length === 0) {
    return <p className="text-gray-500">No products found.</p>
  }

  return (
    <div className="grid grid-cols-3 gap-4">
      {products.map(p => <ProductCard key={p.id} product={p} />)}
    </div>
  )
}
3

Optional Chaining and Nullish Coalescing

Concise defensive mapping
1 min
component.jsx
// ✅ Optional chaining — returns undefined if data is undefined (no error)
{data?.map(item => <Item key={item.id} item={item} />)}

// ✅ Nullish coalescing — falls back to empty array
{(data ?? []).map(item => <Item key={item.id} item={item} />)}

// ✅ Logical AND — only renders if data is truthy
{data && data.map(item => <Item key={item.id} item={item} />)}

// ✅ Array.isArray check — most explicit
{Array.isArray(data) && data.map(item => <Item key={item.id} item={item} />)}

(data ?? []).map() is the safest pattern — it always returns an array to map over. data?.map() returns undefined when data is undefined, which React renders as nothing but can cause type errors in TypeScript.

4

API Returns Unexpected Shape

Data nested differently than expected
2 min
component.jsx
// Always log the raw API response first
useEffect(() => {
  fetch('/api/posts')
    .then(r => r.json())
    .then(data => {
      console.log('API response:', data)
      // Check: is data the array, or is it nested?
      // { posts: [...] }  → setItems(data.posts)
      // { data: { items: [...] } }  → setItems(data.data.items)
      // [...]  → setItems(data)

      // ✅ Defensive: ensure it's an array before setting
      setItems(Array.isArray(data) ? data : data.items ?? [])
    })
}, [])
5

Prop Not Passed — Default Prop Value

Component receives undefined from parent
1 min
components/TagList.jsx
// ❌ WRONG — no default, crashes if tags not passed
function TagList({ tags }) {
  return <div>{tags.map(t => <span key={t}>{t}</span>)}</div>
}

// ✅ CORRECT — default empty array
function TagList({ tags = [] }) {
  return <div>{tags.map(t => <span key={t}>{t}</span>)}</div>
}

// ✅ ALSO CORRECT — PropTypes default
TagList.defaultProps = { tags: [] }

// ✅ TypeScript — explicit optional with default
function TagList({ tags = [] }: { tags?: string[] }) {
  return <div>{tags.map(t => <span key={t}>{t}</span>)}</div>
}

Prevention

Frequently Asked Questions

Why does 'Cannot read properties of undefined reading map' happen in React?+
You are calling .map() on a value that is undefined or null. This happens when: data is still loading (undefined before API response), useState is initialized as undefined instead of [], the prop was not passed to the component, or the API returned a different shape than expected.
How do I fix 'map is not a function' in React?+
The value you are mapping is not an array. Use Array.isArray() to check: if (Array.isArray(data)) { data.map(...) }. Or initialize state as empty array: useState([]) and guard the render until data arrives.
How do I safely map over data that might be undefined?+
Use optional chaining and a fallback: (data ?? []).map(...) or data?.map(...). The first is safer as it renders nothing if data is undefined. The second also works but returns undefined which React renders as nothing.
Map error only on first render — how to fix?+
Your data is undefined during the first render because the API call has not completed yet. Initialize state as an empty array: const [items, setItems] = useState([]) and show a loading indicator while fetching. The empty array maps to nothing, no error.
API data nested differently than expected — map error?+
Always log the raw API response: console.log(data). The array may be nested: data.items, data.results, data.users etc. Access the correct path: data.items.map(...) or destructure: const { items } = await response.json().
React map error after adding TypeScript — how to fix?+
TypeScript caught a real bug — the type system detected that the variable can be undefined. Fix by initializing with an empty array or adding a type guard: if (!data) return null.

Need Expert Help?

We Build Production-Grade React Apps

Softplix builds full-stack React and Next.js applications. Need help with data fetching patterns or error handling? We can help.

Talk to an Engineer