0

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='' />
2
  • Is getLibraryFromId a promise? or a method which returns a result? Commented Jul 23, 2021 at 10:00
  • Also - your useEffect has no array parameters, which means it will run on every change. Ideally you want to pass an empty array to imply it will only ever be on first load.useEffect(() => { setCurrentData(getLibraryFromId(currentID, data)); }, []); Commented Jul 23, 2021 at 10:01

1 Answer 1

1

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=""
        />
      )}
Sign up to request clarification or add additional context in comments.

1 Comment

Yep that'll do it and makes sense! Thanks man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.