Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check net Info in React Native iOS?

I need to check Internet connection in react native iOS

I would try following code:

NetInfo.isConnected.fetch().then(isConnected => {
   console.log(isConnected);
});

that can work fine in react native android application, But it always return 'false' in react native iOS .

like image 461
Saravana Kumar Avatar asked Apr 04 '17 05:04

Saravana Kumar


People also ask

How check network or not in react native?

NetInfoState APItype – Returns the NetInfoStateType of the current connection (cellular, wifi, bluetooth, etc..) isConnected – Boolean value that tells if there is an active network connection. isWifiEnabled (Android only) – Boolean value indicating if wifi is enabled or not.

How do I check my network strength in react native?

If you just want to know whether the device has an active internet connection, you can use e.g. isConnected from React Native's NetInfo: import { NetInfo } from "react-native"; NetInfo.


1 Answers

There is currently an open issue about this in react native's github.

You can see the discussion there, but in short - the fetch is always returning false, but you can work around it by listening to the connection changed event.

Code example from there:

componentDidMount() {
    NetInfo.isConnected.addEventListener('change', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('change', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log(`is connected: ${this.state.status}`);
}

Edit:

Seems like this issue has been worked on. Also, change event was renamed to connectionChange. Updated workaround code:

componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

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

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log(`is connected: ${this.state.status}`);
}

Updated:

The change event type is deprecated. Consider using the connectionChange event type.

like image 196
Moti Azu Avatar answered Sep 21 '22 14:09

Moti Azu