NetInfo in react-native is returning isConnected as false even when network is connected

Viewed 3294

We are using react-native NetInfo in following way.

export default class NetworkStatus extends React.PureComponent {
 constructor(props){
  super(props);

   NetInfo.addEventListener(
     'change',
     this.onConnectivityChange
  ); 
 }

 onConnectivityChange = (status) => {
   NetInfo.isConnected.fetch().then(isConnected => {
     console.log('*********Network status ' + (isConnected ? 'online' : 
    'offline'));
 });
}

Launched the app in Offline Mode. We got the following console.

*********Network status offline.

Then we turned on wifi and it is connected. But we got offline console twice.

*********Network status offline.

*********Network status offline.

Is this a bug in NetInfo Library. Is there a way to fix it.

versions used :

"react": "16.0.0-alpha.6"

"react-native": "0.44.0",

3 Answers

you have to change

NetInfo.addEventListener(
 'change',
 this.onConnectivityChange
); 

to

NetInfo.addEventListener(
 'connectionChange',
 this.onConnectivityChange
);

If you are facing this problem in the simulator then it is because of net connectivity because react-native uses sockets to run the app once you turn off the internet connection sockets gets disrupted and even you turn it on sockets are not restored. Please try using it in actual phone or release mode. It works fine.

componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange)
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange)
  }

  handleConnectivityChange = (isConnected: any) => {
    if (isConnected) {
      this.setState({ isConnected })
    } else {
      this.setState({ isConnected })
    }
  }

I stubbled on this while trying to fix the same problem on an older app which used 0.57.8.

Turns our that react native's NetInfo had a bug which was later fixed.

To fix this I had to change the code to use NetInfo from @react-native-community/netinfo instead of the one that shipped with react native.

I hope this can help others.

Related