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?
4
Answers
You could use
setTimeout()
to delay some actions an example would be:If you want to show after a specific amount of time, you can you setTimeout inside the useEffect. Like this:
You can create a custom hook something like below
or you can use https://tanstack.com/query/v4/docs/react/reference/useQuery
you should use a timer to cache
setTimeout
and then when request not back toshow message or back to cancel. like: