Turn on JavaScript
Pritish Vaidya

How to monitor network changes using Redux Saga in React Native

📅️ January 01, 2019

Redux Saga is an alternate side effect model for redux apps. It is easier to manage, execute, test and catch errors. Rather than implementing the logic to manage the network state in your react component, the side-effects should be handled separately. Redux Saga provides us with eventChannel as an out of the box solution for handling such cases.

network_changes_1

What is an Event Channel?

Redux Saga consists of eventChannels to communicate between external events and sagas _as a factory function. The events are from the event sources _other than the redux store.

Here’s a basic example from the docs:

network_changes_code_1

Things to note:

  • The first argument of the eventChannel is a listener function.
  • The return method is the unregister listener function.

Emitter initializes the listener once _after which all the events from the listener are _passed to the emitter function by invoking it.

How should I hook up Redux Saga’s Event Channel with React Native’s

Network(NetInfo) API?

The React Native’s NetInfo isConnected API asynchronously fetches a boolean which determines whether the device is online or offline.

Dive into the code

First, we need to create a start channel method.

network_changes__code_2

The next step is to listen for the event changes within the channel.

network_changes__code_3

The final step is to pass a custom action to the channel so that the value can be synced using your action.

network_changes__code_4

This channel can be used in our default exported generator by using the call operation.

network_changes__code_5

The exported generator can then be imported and used as a _detached task _using spawn/fork operation in our main saga.

Usage

The above code has added it as a package react-native-network-status-saga to include some of the more useful and cool parameters.

Here are the links

Thanks for reading. If you liked this article, show your support by clapping this article to share with other people on Medium.

More of the cool stuff can be found on my _StackOverflow and GitHub profiles._

Follow me on _LinkedIn, Medium, Twitter for further update new articles._