react-nativereact-native-community-netinfo

NetInfo.addEventListener is called twice in component did mount in IOS


When app lunches, componentDidMount is called and then NetInfo.addEventListener is called twice. Is any solution of it. My code is:

class OfflineMessage extends PureComponent {

    state = {
      isConnected: true
    };

  componentDidMount() {
    NetInfo.addEventListener((state) => {
      this.handleConnection(state.isConnected);
    });
  }

  componentWillUnmount() {
    NetInfo.removeEventListener((state) => {
      this.handleConnection(state.isConnected);
    });
  }

handleConnection = (isConnected) => {
  console.log('status-----', isConnected);
  this.setState({ isConnected });
};

Solution

  • I corrected my code, Now even componentDidMount called twice, if connectivity status changed then only It will print console. Previously whenever connectivity status changed it was printing true, true, false ,false.

    class OfflineMessage extends PureComponent {
    
        state = {
          status: true
        };
    
      componentDidMount() {
        NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);
      }
    
      componentWillUnmount() {
        NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
      }
    
      handleConnectionChange = (isConnected) => {
        const { status } = this.state;
        if (isConnected != status) {
          console.log("connection changes");
          NetInfo.isConnected.removeEventListener('connectionChange');
        } else {
          NetInfo.isConnected.removeEventListener('connectionChange');
        }
      }