Filth
Filth

Reputation: 3228

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='' />

Upvotes: 0

Views: 1019

Answers (1)

Divyesh Kanzariya
Divyesh Kanzariya

Reputation: 3789

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=""
        />
      )}

Upvotes: 1

Related Questions