Getting connected status on React Native

June 09, 2018 0 Comments

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 );  
  • Ping a Website In this case, y'all can try pinging
let req = await fetch('');  
let hasConnection = req.status === 200;  

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.

Tag cloud