react data_error ai_generated true

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

ID: react/cannot-read-undefined-map

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
18 active

Root Cause

Calling .map() on undefined data. Common with async data not loaded yet or wrong API response shape.

generic

Workarounds

  1. 95% success Initialize state with empty array: const [items, setItems] = useState([])
    const [items, setItems] = useState([])

    Sources: https://react.dev/reference/react/useState

  2. 92% success Add loading state check: if (!data) return <Loading />
    if (!data) return <Loading />

    Sources: https://react.dev/learn/synchronizing-with-effects

  3. 88% success Use optional chaining: data?.items?.map(...)
    data?.items?.map(...)

    Sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Dead Ends

Common approaches that don't work:

  1. Add || [] everywhere data is mapped 55% fail

    Masks underlying data issues — undefined data might indicate a real bug

  2. Use try/catch around the render 70% fail

    Components shouldn't need try/catch for normal rendering

Error Chain

Frequently confused with: