Type error: cannot read property ‘map’ of undefined react
Introduction
Working with React is no easy task. You might come up with errors you may not understand. One issue you might experience working with an API is the error, “TypeError: Cannot read property ‘map’ of undefined”. This may throw you off guard and drive you crazy. The problem is not in the API or how you structured your components in react, the main culprit is React itself. If you continue reading below I will walk you through the reason the error exists, a couple of solutions to getting over it, and some demonstrations of the solutions themselves.
What does this mean
What does the cryptic error mean exactly? The answer to this problem is React. The framework has an asynchronous issue. To provide a different perspective to this is that React does not wait for data fetching. It may seem you are mapping over an array, however, the asynchronous behavior of the framework causes major issues and problems rendering your JSX elements. Here is a demonstration below for more clarity.
Solution 1
The solution may seem simpler than you think. One simple solution is by adding an empty array when it comes to fetching data. For example when you’re fetching your API and setting the hook to an initial value just change it to an empty array. This will work because React will go through the map method on an empty array when you're waiting to fetch that API. This won’t cause any issue because there is nothing to render while you’re waiting to fetch the data. 9 times out of 10 we have an empty initial value. setting an array will most likely be the solution to your problem. Here is a demonstration below for better clarity.
Solution 2
If the initial solution does not work you may have to get crafty and do some conditional rendering. This method is efficient and gets you fast results. You want to start out by setting a variable declaration. Onward, create a conditional that automatically evaluates to true. Within the true statement map over your desired array and return it. The last step is optional you can add a loading string in the else statement for a much cleaner UX/UI experience. Here is the full code below.
If the initial solution does not work you may have to get crafty and do some conditional rendering. This method is efficient and gets you fast results. You want to start out by setting a variable declaration. Onward, create a conditional that automatically evaluates to true. Within the true statement map over your desired array and return it. The last step is optional you can add a loading string in the else statement for a much cleaner UX/UI experience. Here is the full code below.