2

In your opinion this is the right approach:

  const [isNetwork, setIsNetwork] = useState(true);
  const [isChangeNetwork, setIsChangeNetwork] = useState(false);



useEffect(() => {
    NetInfo.fetch().then(({ isConnected, isInternetReachable }) =>
      setIsNetwork(isConnected && isInternetReachable)
    );
    const unsubscribe = NetInfo.addEventListener(
      ({ isConnected, isInternetReachable }) => {
        setIsNetwork(isConnected && isInternetReachable);
        setIsChangeNetwork(true);
      });
    return () => unsubscribe.remove();
  }, []);


...

 <Snackbar
          visible={isChangeNetwork}
          onDismiss={() => setIsChangeNetwork(false)}
          duration={3000}
          theme={{ colors: { inverseSurface: isNetwork ? 'green' : 'red' } }}>
          {isNetwork ? "Internet" : "No Internet"}
        </Snackbar>

First I get the error: here: return () => unsubscribe.remove(); Visual studio also tells me:

Property 'remove' does not exist in type 'NetInfoSubscription'.ts(2339)

enter image description here

Can you suggest me a better method?

One problem is that when starting the app, even if there is internet, the Snackbar appears and says there is internet.

Instead I want the Snackbar to appear only in these cases:

  1. It is not there when starting the app
  2. There is a change of state, like here for example:

a) First there is internet (then nothing appears), then there is no internet (then the Snackbar appears)

b) First there is no internet (then the Snackbar appears), then there is the internet (then the Snackbar appears)

Can you give me a hand?

Paul
  • 3,644
  • 9
  • 47
  • 113

1 Answers1

0

Your logic is correct, the only thing is to use unsubscribe(); instead unsubscribe.remove();

useEffect(() => {
    NetInfo.fetch().then(({ isConnected, isInternetReachable }) =>
      setIsNetwork(isConnected && isInternetReachable)
    );
    const unsubscribe = NetInfo.addEventListener(
      ({ isConnected, isInternetReachable }) => {
        setIsNetwork(isConnected && isInternetReachable);
        setIsChangeNetwork(true);
      });
    return () => unsubscribe();
}, []);
Thanhal P A
  • 4,097
  • 3
  • 18
  • 38