Detecting the state of the network
If your code tries to make a request over the network while disconnected – using fetch()
, for example – an error will occur. You probably have error-handling code in place for these scenarios already, since the server could return some other type of error.
However, in the case of connectivity trouble, you might want to detect this issue before the user attempts to make network requests.
There are two potential reasons for proactively detecting the network state. The first one is to prevent the user from performing any network requests until you've detected that the app is back online. To do that, you can display a friendly message to the user stating that, since the network is disconnected, they can't do anything. The other possible benefit of early network state detection is that you can prepare to perform actions offline and sync the app state when the network is connected again.
Let's look at some code that...