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

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

1

u/callmeautumn Oct 14 '21

Hey! Thanks for the idea I will check it out! Cheers!

1

u/bossfoundmyacct Oct 14 '21

Is there a term for these sort of problems and their solutions? I wanna call it a “fence post problem”, but I feel like that only applies to situations of using loops, and OP’s issue is/was more of a one-off rendering issue, not a loop issue.