React — TypeError: Cannot read property ‘map’ of undefined

KJ Osenenko
2 min readApr 11, 2021

--

While building my React application for the final project of Flatiron School’s Software Engineering bootcamp, I encountered a rather annoying bug that gave me a lot of trouble. Many of the resources I found were either outdated as they were written for old versions of React or they did not fully address the issue I was having since they did not involve the redux middleware that I used in my application (full stack application using a Rails API).

The application I was building was a simple reddit clone type of application. When navigating to the ‘show’ page of a specific thread a fetch request would be made to the API to GET the replies for the specific thread. Once a user opened the ‘show’ page the fetch request would be made using the router params with the appropriate post id. Since this is an asynchronous object, the page would try to map an array that did not exist yet causing the error.

Here is my original code:

With this logic, the lifecycle of the React application is attempting to map over the array before the array exists because of the asynchronous object.

The solution I found was:

In this case React will not attempt to map over the array until the array exists, and then it will render the appropriate JSX to show the replies. Until the array exists, I simply rendered a spinner using some bootstrap, but you could use any type of placeholder.

--

--