NetInfo in response-native returns isConnected as false, even when the network is connected

We use adaptive NetInfo as follows.

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 application offline. We have the following console.

********* Offline network status.

Then we turned on wifi and connected. But twice we got a standalone console.

********* Offline network status.

********* Offline network status.

Is this a bug in the NetInfo library. Is there any way to fix this.

Used Versions

:

"respond": "16.0.0-alpha.6"

"react-native": "0.44.0",

+8
source share
3 answers

You have to change

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

at

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

, , - , -, , , . , . .

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

, , 0.57.8.

, NetInfo , .

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

I hope this can help others.

0
source

Source: https://habr.com/ru/post/1682462/


All Articles