9

I'd like to route the user to a certain screen, in case he is not connected to the internet.

I just can't detect if he is connected or not.

I tried this code, but did not work:

async componentWillMount()
{
   if (!await NetInfo.isConnected)
   {
      this.props.navigation.navigate('Saved');
   }
}

Any tested solution to suggest?

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
27mdmo7sn
  • 499
  • 2
  • 6
  • 15
  • Possible duplicate of [Detect network connection in React Redux app - if offline, hide component from user](https://stackoverflow.com/questions/40248639/detect-network-connection-in-react-redux-app-if-offline-hide-component-from-u) – vahdet Jul 19 '18 at 08:28
  • 1
    @vahdet are you sure that the same browser APIs that the linked question uses are available in react-native? – Al.G. Jul 19 '18 at 08:38
  • 1
    At the time of the comment, `react` was among the tags. Not deleteing in case of it could be a helpful link to anyone some time though. Thanks! – vahdet Jul 19 '18 at 08:58
  • 1
    Here's an interesting article https://medium.com/@kulor/creating-an-offline-first-react-native-app-5534d7794969 about why NetInfo isn't necessary the best approach. It explains that NetInfo reports a User as connected when they're connected to a WiFi behind a paywall. The article poses a solution. – Dan Jul 19 '18 at 17:22

5 Answers5

8

Try await NetInfo.isConnected.fetch()

ref : https://facebook.github.io/react-native/docs/netinfo.html#isconnected

Gabriel Bleu
  • 9,703
  • 2
  • 30
  • 43
  • Wait :D , your answer is accepted , but have issue the mobile may have internet connection from WIFI or mobile data your solution works well with the WIFI , but if the mobile is connected from DATA "await NetInfo.isConnected.fetch()" return false; – 27mdmo7sn Jul 19 '18 at 21:35
  • @27mdmo7sn may be related to `ACCESS_NETWORK_STATE` permission on android. – Gabriel Bleu Jul 20 '18 at 07:39
2

You can check using NetInfo . for that you have to add connectionChange event listener like this

componentDidMount() {
        NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange.bind(this));
        NetInfo.isConnected.fetch().done(
            (isConnected) => { this.setState({ isConnected: isConnected }); }
        );

and then remove the event listener in componentWillUnmount

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

And finally the handler method for connection change. I am storing the status in device local storage you can do whatever you want.

handleConnectionChange = (isConnected) => {
        if (isConnected) {
            //ToastAndroid.show('Data sync in process...', ToastAndroid.SHORT);
            AsyncStorage.getItem('offlineData')
                .then((json) => JSON.parse(json))
                .then((data) => {
                    console.log(JSON.stringify(data));
                });
        }
        else { ToastAndroid.show('You are offline.', ToastAndroid.SHORT); }

        this.setState({ isConnected: isConnected });
    }

Don't forget to add NetInfo from react-native :)

Kishan Oza
  • 1,707
  • 1
  • 16
  • 38
2

Another solution to your case (one without using isConnected property) is to use the object returned from the event handler directly like that:

componentDidMount() {
  NetInfo.addEventListener('connectionChange', this.handleNetworkChange);
}

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

handleNetworkChange = (info) => {
    if (info.type === 'none') {
      this.props.navigation.navigate('Saved');
    }
};

According to NetInfo documentation:

connectionChange event fires when the network status changes. The argument to the event handler is an object with keys:

type: A ConnectionType (listed above)

effectiveType: An EffectiveConnectionType (listed above)

The connection type can be one of the following : none, wifi, cellular, unknown.

Ideally you can store this information to your redux store and the listener to a root component.

We had a weird bug when using isConnected similar to the one you mentioned @Gabriel Bleu but for us, the NetInfo.isConnected.fetch() returned false only when the Android device was awake after some period of inactivity.We used it to display offline warning for users, so the warning never left. I found this solution on a Spencer Carli's course and it seems to work better but depending on your needs, you might want to use isConnected combined with the above code.

Community
  • 1
  • 1
Vely
  • 381
  • 5
  • 8
1

This is a great example to check online or offline and even you can have connection change information too. Source

NetInfo.isConnected.fetch().then(isConnected => {
  console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
  console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
  NetInfo.isConnected.removeEventListener(
     'connectionChange',
     handleFirstConnectivityChange
  );
}
NetInfo.isConnected.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
0

There are two issues with your code currently.

  1. In newer versions of react life-cycle method componentWillMount is deprecated.
  2. Newer versions of react-native have extracted the NetInfo Module out of the core. Use @react-native-community/netinfo instead.

In order to achieve the desired behavior you should do something like this.

import NetInfo from "@react-native-community/netinfo";

class CheckConnection extends Component {

    componentDidMount() {
        
        NetInfo.fetch().then(state => {
            handleConnectionState(state)
        }); 
        
    }
        
    handleConnectionState(state) {
        console.log("Connection type", state.type);
        console.log("Is connected?", state.isConnected);
        ... your code to handle the lack of connection
        
    }

}
twboc
  • 1,452
  • 13
  • 17