Search code examples
reactjsreact-hooksuse-effect

React Set State within useEffect refresh page


My application has a strange bug and I think it's to do with asnyc - where by if I navigate to a new page by clicking on an element my page data renders correctly.

However, if I refresh said page I get errors where my data is undefined - I think that's to do with react not having enough time to render the state change?

Is there a way to get around this - perhaps I'm trying to set my state incorrectly within a useEffect however, I want to update on "componentDidMount"?

Here is my useEffect code

useEffect(() => {
    setCurrentData(getLibraryFromId(currentID, data));

});

Usage:

<img src={`https://image.tmdb.org/t/p/original/${currentData.backdrop_path}`} alt='' />

Solution

  • you are getting data from API right so before that you need to add check if object is blank or not if blank then render nothing or display placeholder image.

          {currentData?.backdrop_path && (
            <img
              src={`https://image.tmdb.org/t/p/original/${currentData.backdrop_path}`}
              alt=""
            />
          )}