React typeerror: cannot read property ‘map’ of undefined

React throws typeerror: cannot read property ‘map’ of undefined, when we try to use anything but arrays. According to MDN documentation

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Map iterates over each value of the array and after required computation, returns it. It constructs a new array and after completing all the iterations, it returns the whole array.

We use map in React to store JSX which needs to generated in loop.

There are many situations where we can get typeerror of cannot read property ‘map’ of undefined. Remember these points –

  1. Check if you are using map on array or something else like objects.
  2. If you are getting the array from other sources then it is safe to type check it before using map.

For example, the below code will not work because we are using map on object.

const superheroObj = {
  0: 'Captain America',
  1: 'Ironman',
  2: 'Hulk',
  3: 'Thor',
}

const newSuperheroArray = superheroObj.map((hero, index) => {
  return 'Avenger - ' + hero;
})

Now to make it work, we need to first convert superheroObj into Array –

const superheroObj = {
  0: 'Captain America',
  1: 'Ironman',
  2: 'Hulk',
  3: 'Thor',
}

const superheroArray = Object.values(superheroObj)

const newSuperheroArray = superheroArray.map((hero, index) => {
  return 'Avenger - ' + hero;
})

Now check the code when we provide a wrong, undefined entity to the map function –

const returnSuperheroArray = (myArray) => {
  return myArray.map((hero) => {
    return 'Avenger - ' + hero;
  });
}

console.log(returnSuperheroArray());

The above code will throw typeerror cannot read property ‘map’ of undefined. This is because we have not supplied any parameter to the returnSuperheroArray function while it is expecting an array.

This is not a mistake or bug else its a genuine condition. Suppose you are getting this superheroArray from backend through API call. Now you can’t be sure if API is sending the correct data. That’s why we have to deal with this situation explicitly.

To prevent the error, you can typecheck the argument value for being an Array. We could use typeof function provided by javascript but its not very versatile as it returns object as type of array. Luckily, javascript provides another function for checking array type specifically – Array.isArray().

Let’s use isArray and make our above code safe from React type error –

const returnSuperheroArray = (myArray) => {

  if(!Array.isArray(myArray))
    return "Please provide a valid array";

  return myArray.map((hero) => {
    return 'Avenger - ' + hero;
  });
}

console.log(returnSuperheroArray());

    Tweet this to help others

Live Demo

Open Live Demo