7

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 .

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This might be very late. but.....NetInfo's "change" event is deprecated. Listen to the "connectionChange" event instead.
this approach causes a warning if the isConnected.fetch promise is resolved after the component is unmounted, due to calling setState on an unmounted component
0

By using this module you can subscribe to network state updates

const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Is connected?", state.isConnected);
});

and also you can find if the internet is reachable with the currently active network connection.

console.log("Is Internet Reachable?", state.isInternetReachable);

I also explained usage of react-native-netinfo and its features here with source code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.