I have a loading skeleton indicator when I’m loading data. What I want to do is to take into consideration users with slow internet connection. So I decided to have a skeleton loading indicator which lasts until the fetching completes. However, I want to show a toast maybe 5 seconds after the loading starts, to indicate to the user that he/she has a slow internet connection. So far I have something like:
useEffect(() => {
const timer = setTimeout(() => {
// Show toast here
}, 5000);
if (!loading) clearTimeout(timer);
}, [loading])
But this doesn’t seem to work because even after loading
is set to false, the toast still appear. What am I missing here or is there an alternative way to do this?
2
Answers
As is the value of
timer
will be different each time the useEffect runs so the clearTimeout won’t stop the previous timeout. Consider doing the clearTimeout in a cleanup function.You need to keep track of the timeout ID returned by
setTimeout
and then useclearTimeout
in the cleanup ofuseEffect
.