Skip to content

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

Error message

                Cannot read properties of undefined (reading 'map')
              

Quick summary

You called `.map()` on a variable that is `undefined` — usually because data hasn't loaded yet or a prop wasn't passed.

Why this happens

  • Data is initially undefined before an API call completes

  • A prop was not passed from the parent component

  • The API response has a different shape than expected

  • Optional chaining was not used on nested object access

Minimal example

✗ Broken code
function List({ items }) {
  return items.map(item => <li key={item.id}>{item.name}</li>); // items is undefined
}
✓ Fixed code
function List({ items = [] }) {
  return items.map(item => <li key={item.id}>{item.name}</li>);
}

Providing a default value items = [] ensures the prop is always an array, so .map() never fails.

How to diagnose

  • Log the variable before calling .map() to see its value

  • Check if the data is loaded before rendering the list

  • Verify the parent is passing the prop

How to fix

  • Initialize state with an empty array: useState([]) instead of useState()

  • Add a null check before mapping: data?.map(...) or data && data.map(...)

  • Provide a default prop value: function List({ items = [] })

How to prevent

  • Always initialize array state with []

  • Use optional chaining (?.) for nested property access

  • Define default prop values

Related Resources

Related Glossary

Related Lessons

← Back to language