Ravi Sharma
Ravi Sharma

Reputation: 527

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

Upvotes: 1

Views: 2202

Answers (2)

Ravi Sharma
Ravi Sharma

Reputation: 527

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');
    }
  }

Upvotes: 0

Akila Devinda
Akila Devinda

Reputation: 5502

This is expected behaviour according to github issue page. You should not make any assumptions about when or how often your listen is called and you should expect differences between platforms. This is because each platform handles networking different and we mirror that rather than trying to make everything 100% the same.

This is likely because a value other than isConnected is changing, for example the network type. We fire the event whenever the system provides some new network information and pass this on to you.

If you do not want to re-render when the information is the same, this is up to you to implement either using componentShouldUpdate or by managing the state in something like Redux. The library will update you whenever it gets and update and you shouldn't make assumptions about how often or when it will provide these.

Refer

Refer

Upvotes: 1

Related Questions