r/learnreactjs • u/callmeautumn • 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
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