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
Rendering data before it loads from an API
Accessing deeply nested properties without checking existence
Array method (map, filter, find) called on undefined
Props or state initialized as undefined
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:
401 Unauthorized Error
Learn what a 401 Unauthorized error means, common causes, and how to fix authentication failures in your web applications.
403 Forbidden Error
Learn what 403 Forbidden means, how it differs from 401, and how to fix access denied errors in your applications.
404 Not Found Error
Learn what 404 Not Found means, common causes, and how to fix broken links and missing resources on your website or API.
429 Too Many Requests Error
Learn what 429 Too Many Requests means, how rate limiting works, and how to handle or avoid hitting API rate limits.