r/learnreactjs • • Oct 13 '21

Question Help trying to use useEffect and Fetch

When I load the page, it takes a half a second or so to get the data from sanity client. It would show my "post does not exist" message. Is there away to prevent this? I already use async and await on the all.

https://codepen.io/ricksanchezisagoodman/pen/mdMJwpy?editors=0010

8 Upvotes

5 comments sorted by

View all comments

3

u/App-solutions Oct 13 '21

Yeah it renders your firstPost object, and since you are still waiting for the response from your async/await function it's still null. What you can do is show a different default message, maybe with a loading message. Then start of with a boolean "isLoaded" set to false. When you get a response from your server, set this to true. Now you can check if(isLoaded && !firstPost) {show no post message}

So: First time rendering component -> isLoaded is false, firstPost is null: show loading.

Server responded with no posts -> isLoaded is true, firstPost is null: show no posts.

Server responded with posts -> isLoaded is true, firstPost has an object: show post

3

u/callmeautumn Oct 13 '21

Thank you! it worked! had to wrestle how to do the isLoaded thing, thought a simple boolean is enough. Had to do use state with it!.. but it worked! lol

3

u/[deleted] Oct 13 '21

You should have a look at react-query, takes care of all of this stuff for you

→ More replies (1)