Behind 'Error : Cannot read property 'map' of undefined'

March 09, 2022

When we develop a web app using React, we frequently accept an error message:

Error : Cannot read property 'map' of undefined

What’s happened and how to solve it?

What’s the cause?

in Javascript, map is a property that is only had by a variable with type array. Thus, if there is a non-array variable that meets .map, would cause an error.

let hihi = "some string"

hihi.map( ... ) // ERROR
let hihi = ["a","b"]

hihi.map( ... ) // NO ERROR

Although the array is empty, it would not cause an error

let hihi = []

hihi.map( ... ) // TIDAK ERROR

Thus, when a variable with type undefined meets map, this error message will appear

let hihi = undefined

hihi.map( ... ) // ERROR
// Cannot read property 'map' of undefined

That’s is the meaning of

Error : Cannot read property 'map' of undefined

I have assigned an array to the variable, why does the error message still appear?

Such a case frequently happens when we work with React JS. The question is, which one was executed earlier? The assignment or the map?

Let’s observe this component :

  const [fruits, setFruits]=useState(undefined)

  useEffect(() => {
        fetchData...
        setFruits(res.data)   // res.data berisi array
  }, [])

  return (
    <div>
      { fruits.map(item => <li> {item} </li>) }
    </div>
  )

On the example above, we already assign an array to the fruits, but this error message still appear

Error : Cannot read property 'map' of undefined

Why?

Note that, in React JS, useEffect is executed AFTER the component rendered

As a consequence, when those components are called, React will render the component (including fruits.map(...)). After the initial render, React executes useEffect

Therefore, when fruits.map(...) is executed, the variable fruits have not been assigned yet with an array. That’s why the error message appeared

How to solve?

Solution 1

Use empty array as intial state

const [buah, setBuah] = useState([])

Since an array, even if empty, also has a property map. Thus, this would not cause an error. An empty array that is meet map, would return nothing

Solution 2

Use && operator

fruits && fruits.map(item => <li> {item} </li>)

Thus, JS will check the value of fruits. If the value of fruits is undefined, JS will not continue to execute fruits.map(...). So that would not cause an error.

If the value of fruits has been assigned (with array), JS will continue to execute fruits.map(...)

This is because the && operator always returns the first falsy value. You can see here for more explanations

Solution 3

Use optional chaining.

Actually, this is same with Solution 2, but with shorter writing

fruits?.map(item => <li> {item} </li>)

You can see here for more explanations

Hope you enjoyed this blog. Support and comment here 👇👇👇


Galih Pradipto Wisnujati
FE/JS Developer 🇮🇩