Error Encyclopedia

Cannot Read Properties of Undefined Error

Fix 'Cannot read properties of undefined (reading map)' and similar errors in React. Learn how to handle async data and null checks.

What Does This Error Mean?

This error occurs when you try to access a property or method on a value that is undefined. In React, this commonly happens when rendering data that hasn't loaded yet, or accessing nested properties on an object that doesn't exist.

Common Causes

1

Rendering data before it loads from an API

2

Accessing deeply nested properties without checking existence

3

Array method (map, filter, find) called on undefined

4

Props or state initialized as undefined

5

Optional function parameter not provided

How to Fix It

Use optional chaining

Use ?. to safely access nested properties without crashing.

const user = null

// ❌ TypeError: Cannot read properties of null
console.log(user.name)

// ✅ Safe access
console.log(user?.name) // undefined, no error
console.log(user?.address?.city) // undefined, no error

// In JSX
return <p>{user?.name ?? "Guest"}</p>

Use default values with nullish coalescing

Provide fallback values when data is undefined.

function UserProfile({ user }) {
  // Provide defaults for undefined values
  const name = user?.name ?? "Anonymous"
  const email = user?.email ?? "No email"
  const items = user?.items ?? []
  
  return (
    <div>
      <p>{name}</p>
      <p>{email}</p>
      {items.map(item => (
        <span key={item.id}>{item.name}</span>
      ))}
    </div>
  )
}

Show loading state

Conditionally render content only after data has loaded.

function UserList() {
  const [users, setUsers] = useState(null)
  const [loading, setLoading] = useState(true)
  
  useEffect(() => {
    fetch("/api/users")
      .then(res => res.json())
      .then(data => {
        setUsers(data)
        setLoading(false)
      })
  }, [])
  
  if (loading) return <p>Loading...</p>
  if (!users) return <p>No users found</p>
  
  return users.map(user => <div key={user.id}>{user.name}</div>)
}

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: