I have a reactJS app that calls an API using a hook:
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const res = await fetch("/api/r/" + sid);
const result = await res.json();
setResult(result);
setIsLoading(false);
};
fetchData().catch(console.error);
}, [sid]);
sometimes this API takes a long time to return all the data, in there a way to trigger an event after n seconds if I didn’t receive the data yet, so I can show a message to the user?
>Solution :
If you want to show after a specific amount of time, you can you setTimeout inside the useEffect. Like this:
Edit: Remember to remove/clean your timeout on a useEffect cleanup function.
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const res = await fetch("/api/r/" + sid);
const result = await res.json();
setResult(result);
setIsLoading(false);
};
fetchData().catch(console.error);
// I am using 1 sec as an example
const messageTimeout = setTimeout(()=>{
showMessage();
}, 1000);
return () => clearTimeout(messageTimeout);
}, [sid]);