Skip to content
Advertisement

Why does my React app disappear when I run it

Whenever I get data on my page, after a few seconds, my whole react app disappears as in the root div in the html is left completely empty like this <div id="root"></div> as if there is nothing. This is happening on all my other projects too even when I create a new one, this disappearing of the react keeps happening sometimes even without adding any logic, it refuses to render plain html. The errors I get for now on this current project on the console is this

characters.map is not a function

I know not what could be causing this but my code looks like this for now starting with the App.js file. I am extracting data from an api.

JavaScript

And then followed by the CharactersListing page which is supposed to render all the characters of the show

JavaScript

And finally, the CharacterCard.js

JavaScript

I do not know what could be causing this. I have never had this issue it just started today. What could be causing it

Advertisement

Answer

Issues

The issue is that you are not setting the characters state to what you think it is. response.json() returns a Promise object and doesn’t have a map property that is a function to be called.

The useEffect hook is also missing a dependency, so anything that triggers this BadListings component to rerender will also retrigger this useEffect hook, which updates state and triggers another rerender. The code is likely render looping.

Solution

  • The code should wait for the response.json() Promise to resolve and pass that result value into the characters state updater function. Note that I’ve also rewritten the logic to use async/await with try/catch as it is generally considered anti-pattern to mix async/await with Promise chains.
  • Add a dependency array to the useEffect hook. Since I don’t see any dependencies use an empty array so the effect runs only once when the component mounts.

Promise chain Example:

JavaScript

async/await Example:

JavaScript

Don’t forget to add a React key to the mapped characters:

JavaScript

Edit why-does-my-react-app-disappear-when-i-run-it

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement