Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if the user is connected to the internet?

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?

like image 911
27mdmo7sn Avatar asked Jul 19 '18 08:07

27mdmo7sn


People also ask

How do you check if you are connected to the internet?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.

How can you tell if someone is offline?

We can detect if the user is online or offline by using the online property on the navigator object. Additionally, online and offline events will be triggered if the user's internet status changes.

Is connected to internet by which device?

The primary piece of hardware you need is a modem. The type of Internet access you choose will determine the type of modem you need. Dial-up access uses a telephone modem, DSL service uses a DSL modem, cable access uses a cable modem, and satellite service uses a satellite adapter.


2 Answers

Try await NetInfo.isConnected.fetch()

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

like image 61
Gabriel Bleu Avatar answered Sep 25 '22 00:09

Gabriel Bleu


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 :)

like image 44
Kishan Oza Avatar answered Sep 25 '22 00:09

Kishan Oza