Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to trigger an event after n seconds inside a react useEffect hook

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading