0

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
    }
}
tharwi
  • 67
  • 11

3 Answers3

1

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

  • But I want to run the functions only once – tharwi Nov 03 '22 at 10:13
  • @tharwi If your `isConnected` value doesn't change after that, then it will only run once (when it flips from `null` to a boolean) – Terry Nov 03 '22 at 10:14
  • You can wrap the functions in an if block inside the hook. That way once the isConnected is changed the functions would run. – Abhishek Solanki Nov 03 '22 at 10:14
  • @Terry, isConnected value will resolve to true or false immediately. Then it will change over time. But I want to run the function once even though the value changes over time. But I need the internet connection to run those – tharwi Nov 03 '22 at 10:25
1

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]);
E. Dn
  • 940
  • 1
  • 9
  • 21
0

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]);