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

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

Related Tags
  • Error,
  • javascript short,
  • react js short,
  • reactjs error

Most user interfaces have some kind of list. Whether it’s a display of data returned from an API or simply a drop-down list in a form, lists have become a cornerstone element in web applications. It is common to map over a set of data to render these lists, and bugs will inevitably occur.

As a result, the TypeError Cannot read property 'map' of undefined is very common and one of the first errors that developers will be confronted with. It occurs when the variable being executed is of a different type than expected. Recognizing the error and the root cause will save you valuable time in the long run.

In this article, you’ll learn about the TypeError Cannot read property 'map' of undefined, how it happens, how it can be fixed, and what you can do to mitigate this error in the future.

What Is the TypeError Cannot Read Property Map of Undefined

Frontend developers are accustomed to running into errors that prevent their applications from compiling or rendering properly. TypeErrors, in particular, are very common. These represent an error occurring because the value is of a different type than the one expected. It’s one of the most generic and common JavaScript errors that developers experience.

Understanding why they happen will reduce the time needed to debug and fix them. These errors will stop the execution of a program and, therefore, will be detrimental to the user experience if they are not dealt with - errors can cause an application or UI code to crash, resulting in an error pages, blank spaces or blank pages in your application.

How to Understand and Prevent the Error

In this section, you’ll discover what causes the TypeError Cannot read property 'map' of undefined and how to prevent it.

What Causes the Error

In JavaScript specific methods live under specific objects. For instance, String.prototype.split, or split for short, is a function that takes a string and divides it into substrings. It lives under the standard built-in object string and accepts nothing else. If you were to give anything other than a string to the split method, you would get a TypeError. Giving it null, for example, throws the TypeError Cannot read property 'map' of undefined.

This is what makes TypeErrors so common. They can happen any time a value or variable is used, assuming that value is one type when it is actually another.

In the case of map, this method lives on the Array prototype. So calling map on anything other than on an Array will throw a TypeError.

When Does the Error Occur

The TypeError Cannot read property 'map' of undefined occurs in the following situations:

Querying an API

In a perfect world, APIs would be consistent. They would always return the requested data in the desired format. In this scenario, they would be easy to parse and never change.

Unfortunately, in the real world, APIs can be inconsistent. The response might be in a different format than you expected, and if you don’t add some checks, your code could run into some issues.

Here is an example using Nationalize.io, an API predicting the nationality of a name passed as a parameter:

    // Working fine
    const name = 'marie'
    fetch(`https://api.nationalize.io/?name=${name}`)
      .then(res => res.json())
      .then(data => {
       // Data returned : { country: [{country_id: 'RE', probability: 0.0755}, ...], name: "marie"}
        data.country.map((country_details) => console.log(country_details))
    });

    // Throwing an error
    const emptyName = ''
    fetch(`https://api.nationalize.io/?name=${emptyName}`)
      .then(res => res.json())
      .then(data => {
       // Data returned: { error: "Missing 'name' parameter"}
       const { country } = data
       country.map((country_details) => console.log(country_details))
      // Throws TypeError cannot read property ‘map’ of undefined
    });

In the second fetch, there is no country key in the data object, making it undefined. Calling the map function on it throws a TypeError.

Typing Errors

Developers are humans and, therefore, make typos. Similar to the previous example, if you access a property that doesn’t exist on an object, the value will be undefined. Calling the map method will throw the TypeError Cannot read property 'map' of undefined:

    const library = {
      name: "Public library",
      books: [“JavaScript complete reference guide”]
    }
    // ‘bookss’ is not a property of library, so this will throw an error
    library.bookss.map(book => console.log(book))

Trying to Use a Variable Before It’s Set

It’s easy to make a call and forget to take into consideration whether it’s an asynchronous one. When a value is populated asynchronously, accessing it too early will result in an error, as the value might still be undefined:

    const fetchCountries = (name) => {
        fetch(`https://api.nationalize.io/?name=${name}`)
          .then(res => res.json())
          .then(data => {
            console.log(data)
            return data
          });
    }

    const name = 'marie'
    const countriesData = fetchCountries(name)
    console.log(countriesData)

The result of this code is the console logging on line 12 will execute before the fetch call is done and, therefore, before the one on line 5. At this point, countriesData is undefined, and calling map on it would throw an error:

Typeerror: cannot read property map of undefined

The asynchronous aspect is something that React developers have to be particularly wary of. Children components will inherit data through props from their parents, but if the parent isn’t done fetching or computing the necessary data before the child starts rendering, this will also throw an error:

How to Mitigate the Error

The first thing you can do to mitigate this error is to use TypeScript. This strongly typed programming language will warn you ahead of time if you use an unacceptable type:

Typeerror: cannot read property map of undefined

The second way you can mitigate the error is through conditional checks to ensure the value is available before trying to use it. It’s particularly helpful in React, wherein developers regularly use conditional rendering to avoid undefined variables.

Using the previous library and books example, here is a way to use conditional check and rendering but only when set:

    const BookList = ({books}) => {
      return(
        <div>
          {
            Array.isArray(books) && books.map(book => <div>{book.title}</div>) //Check if books is not null to map over it
          }
        </div>
      )
    }

    function App() {
      const books = getBooks(...) // asynchronous hook to grab the list of books
      return (
        <BookList books={books} />
      )
    }

    export default App;

The third solution is optional chaining. This simple operator will short-circuit and return undefined if you call a function on a property that doesn’t exist:

    const library = {
      name: "Public library"
    }
    // books is not a property of library, but with the ? operator, this only returns undefined
    library.books?.map(book => console.log(book))

Finally, you can wrap your call in a try-catch block. You can read more about try-catch here. In the case of API calls that may fail and return error messages, like the first example, you can also use a catch() after your then () function to handle errors.

For this situation, libraries such as Axios are preferred over fetch, as the latter will only throw an error on network issues and not on API errors (such as a 500). Axios, on the other hand, comes with error handling:

    const param = ''
    axios.get(`https://api.nationalize.io/?name=${param}`)
      .then(data => {
        // This will not get executed
        data.country.map((country_details: any) => console.log(country_details))
      })
       .catch(error => console.log(error));

You can read more about Axios vs. Fetch here.

Meticulous and TypeErrors

Meticulous is a tool to easily create UI tests without writing code and without requiring a staging environment. Use their CLI to open an instrumented browser which records your actions as you execute a workflow on your web app.

This sequence of actions can then be used to create a test, which will prevent regressions like TypeErrors. Meticulous captures a screenshot at the end of a replay. Screenshots can then be diffed in order to create a simple test. It's easy to integrate Meticulous tests into your continuous integration system, like GitHub Actions.

This allows you to detect regressions and prevent bugs from reaching production. For more information about Meticulous, don’t hesitate to check out the official docs.

Conclusion

JavaScript developers have to deal with many different kinds of errors. As you learned in this article, TypeErrors are one of the most common. You learned more about what they are, what a few possible causes are, and how to mitigate them.

Over the years, each developer builds a little toolkit of tips and tricks to help them accomplish their job quicker. Keeping in mind all the possible solutions listed in this article will speed up your development and reduce the time spent hunting bugs.

Authored by Marie Starck

How do you fix TypeError Cannot read property map of undefined?

The "cannot read property 'map' of undefined" error occurs when we call the map() method on an undefined value, most often when the map method is called before the data from an API request has arrived. To solve the error, initialize the value you're mapping over to an empty array.

How do you fix Cannot read properties of undefined React?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

How do I read a map in React JS?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.

How do I fix type error in React?

The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.