How to monitor network changes using Redux Saga in React Native
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.
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:
Things to note:
- The first argument of the
eventChannelis 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
The React Native’s NetInfo
isConnected API asynchronously fetches a
boolean which determines whether the device is
Dive into the code
First, we need to create a start channel method.
The next step is to listen for the event changes within the channel.
The final step is to pass a custom action to the channel so that the value can be synced using your action.
This channel can be used in our default exported generator by using the call operation.
The exported generator can then be imported and used as a _detached task _using spawn/fork operation in our main saga.
The above code has added it as a package
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.