I’m working on a pokedex project that uses React. Right now the objective seems simple but I’ve run into a problem. I am calling an API using fetch(), saving the res.json to state, and trying to pass the data as a prop into a React component.
I believe the problem is that the JSX is being read before the response comes back and so is undefined at the time it is called. I’m not very experienced with using async/await/promises so hopefully this is something simple.
This is a very common problem. One solution would be to make that child component able to handle the “no data” state it gets in the beginning.
I will often do something like:
if (!data) {
return null;
}
I put that right before the “real” render. If the component returns null, it just won’t render. There are other ways, too. You can also get more sophisticated and have loading spinners or loading skeletons and error handling/retry, etc.
But yeah, most of us ran into the same problem you’re facing, it’s very common.
I’m too tired to look at your code atm, but I at least wanted to pass that along.
Thanks for the advice! I thought of that, but I was unsure of a way to “refresh” the component so that it loads the picture as soon as the response comes through. Do you have any suggestion for that?
… I was unsure of a way to “refresh” the component so that it loads the picture as soon as the response comes through.
That is the magic of React. If you change the props you are passing, it will automatically update (unless you’ve deliberately messed with the refreshing, like with React.memo or shouldComponentUpdate). That is part of the beauty of how React works - you don’t have to worry about that stuff. Unless you’re preventing it, a component should update when its props or state change.