How to run a useEffect once after internet connected value is set to true?

390 views Asked by At

I'm trying to run several functions in a useEffect after the internet connection state resolves to true. But at the start, the status will be null and then it will resolve to true. As a result the rest of the functions will not be invoked. How to resolve this conflict?

I want to run the functions only once

const Component = () => {
    const {isConnected} = useNetInfo();
    
    useEffect(() => {
        runFunctionOne();
        runFunctionTwo();
    }, []);

    const runFunctionOne = () = {
        if (!isConnected) return;
        // rest
    }

    const runFunctionTwo = () = {
        if (!isConnected) return;
        // rest
    }
}
3

There are 3 answers

4
Abhishek Solanki On

You can try passing isConnected as a dependency to the useEffect. As a result, the useEffect hook will rerun whenever isConnected is changed.

1
E. Dn On

If you want your effect to run only once, you should be aware of multiple connection triggers. Otherwise if you loose your connection after being online, the effect will be triggered again once you're online again.

const wasConnectedRef = useRef(false);

useEffect(() => {
  if (isConnected && !wasConnectedRef.current) {
    runFunctionOne();
    runFunctionTwo();
    wasConnectedRef.current = true;
  }
}, [isConnected]);
0
Elbashir Saror On

Either you use setTimeout to make sure you are connected:

 useEffect(() => {
       // functions will not be called until 6s have passed, hopefully you will be connected by then.
        setTimeout(() => {
            runFunctionOne();
            runFunctionTwo();       
        }, 6000);
    }, []);

If you will try to connect multiple times, even after 6s have passed, then you need to add isConnected as a dependency

}, [isConnected]);