DEV Community

Ng Chen Hon
Ng Chen Hon

Posted on

Getting connected status on React Native

We may need to know if a device is connected to the internet sometimes on React Native.

What the Doc said

We should be using NetInfo.isConnected.fetch() to get a boolean denoting the device is connected or not.

In fact

Up until the current newest v0.55, it is still observed that NetInfo.isConnected.fetch() works properly on Android only. It tends to return false on iOS. It is a known bug.

Solutions from the internet

  • Use Event Listener We can add an event listener and listen to changes in network status.
onInitialNetConnection = (isConnected : boolean) => {
    console.log(`Is initially connected: ${isConnected}`);
    NetInfo.isConnected.removeEventListener('connectionChange', this.onInitialNetConnection);
};

constructor(props : Props) {
    super(props);
    NetInfo.isConnected.addEventListener(
        'connectionChange',
        this.onInitialNetConnection
    );
}
Enter fullscreen mode Exit fullscreen mode
  • Ping a Website In this case, y'all can try pinging google.com
let req = await fetch('https://www.google.com');
let hasConnection = req.status === 200;
Enter fullscreen mode Exit fullscreen mode

Ugly, but it works.

  • Use NetInfo.isConnected.fetch() a Few Times ???

Tested on < v0.55, I discovered that calling NetInfo.isConnected.fetch() multiple times on componentWillMount of the root component of the app actually works.

On v0.55, this seems to stop working.

¯\_(ツ)_/¯
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
taskonomyapp profile image
Taskonomy

let req = await fetch('google.com');
let hasConnection = req.status === 200;

giving me an error

Collapse
 
mutatedbread profile image
Ng Chen Hon

Hi,

Forgive me for this very late reply.

I am presuming you are getting the error when running it on iOS.

I had not taken into consideration that any network requests on iOS must be https or have the url placed into exception when I was writing this.

Please try with the below if you are still stuck on this.

let req = await fetch('https://www.google.com');
let hasConnection = req.status === 200;