Fred A
Fred A

Reputation: 1764

Correct way to subscribe and unsubscribe React Native Netinfo

Based on the documentation in here to subscribe and unsubscribe Netinfo listener - https://github.com/react-native-netinfo/react-native-netinfo

I define the listener method in a common file and export it

/* util.js */
function listener(){
  Netinfo.addEventListener(state => /* something in here */);
}

export { listener };

Then in a React component

import { useEffect } from 'react';
import { listener } from 'util';

const exampleComponent = props => {
  
  // then on useeffect
  useEffect(() => {
    listener() // to subscribe

    return () => listener(); // to unsubscribe
  }, []);

  return <ExampleComponent />
}

Is this the correct way to setup Netinfo listener if i want to make listener as an exportable method that can be setup anywhere (altho by logic it should only be set up on the main file in the app, but just for the sake of question)?

Im not sure how calling listener the first time will subscribe Netinfo listener and calling it again will unsubscribe it.

Upvotes: 0

Views: 3160

Answers (2)

Ahmed Gaber
Ahmed Gaber

Reputation: 3976

Is this the correct way to setup Netinfo listener if i want to make listener as an exportable method that can be setup anywhere (altho by logic it should only be set up on the main file in the app, but just for the sake of question)?

if you want to setup once and use it many times, no need to do that by yourself, you can use useNetInfo()

import {useNetInfo} from "@react-native-community/netinfo";

const YourComponent = () => {

  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

Upvotes: 2

Shivam
Shivam

Reputation: 2359

You can try this,


    import NetInfo from "@react-native-community/netinfo";
    
    const [isConnected, setIsConnected] = useState(true);
    
    NetInfo.fetch().then(state => {
            if (state.isConnected && state.isInternetReachable) {
                setIsConnected(true);
            } else {
                setIsConnected(false);
            }
        });
    
    useEffect(() => {
            const unsubscribe = NetInfo.addEventListener(state => {
                if (state.isConnected && state.isInternetReachable) {
                    setIsConnected(true);
                } else {
                    setIsConnected(false);
                }
            });
            if (isConnected) {
                
            } else {
                unsubscribe();
            }
        }, []);

Upvotes: 1

Related Questions