0

I need to condition which function will be called based on internet connection in a React App, for example:

if (connected) {
   call function Y()
} else if (!connected) {
   call function X()
}

How could I do that? I've tried it with NetInfo and with navigator.online, but I couldn't make it work.

Berg_Durden
  • 1,531
  • 4
  • 24
  • 46

2 Answers2

1

From the MDN docs on navigator.onLine:

If the browser doesn't support navigator.onLine it will always come out as false/undefined.

To see changes in the network state, use addEventListener to listen for the events on window.online and window.offline, as in the following example:

window.addEventListener('offline', function(e) {
console.log('offline'); });

window.addEventListener('online', function(e) { console.log('online');
});
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35
1

Browsers implement navigator.online property differently.

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connection like Chrome and Safari giving false positives.

I Would suggest listening to the online event and if you get True then to double sure make an ajax request to any public domain like google or your own

[Based On][1] [1]: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine