skip to Main Content

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


  1. 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.

    useEffect(() => {
        if (loading) {
          const timer = setTimeout(() => {
              // Show toast here
          }, 5000);
          return () => clearTimeout(timer); 
        }
    }, [loading])
    
    Login or Signup to reply.
  2. You need to keep track of the timeout ID returned by setTimeout and then use clearTimeout in the cleanup of useEffect.

    useEffect(() => {
        let timer;
        if (loading) {
            timer = setTimeout(() => {
                // Show toast here
            }, 5000);
        }
    
        return () => {
            if (timer) clearTimeout(timer);
        };
    }, [loading]);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search