Handle Side-Effects with Redux-Saga
Introduction
One of hardest parts in developing and maintaining React/Redux application is handling asynchronous actions: timeouts, requests/response handling, interaction with third-party stores, different callbacks and so on without сomplicating logic into actions-creators and reducers. In this post, I’m going a real project to show you how to move all side-effects ( and not only ) away from action-creators. All of this in a way that makes them as clean as possible with Redux-Saga.
What is redux-Saga?
Redux-Saga is a library that aims to make application side effects easier to manage, more efficient to execute and simpler to test. If you were working on some React/Redux projects, you were probably using Redux-Thunk
for asynchronous work. Redux-Thunk is the standard way to perform asynchronous operations on Redux. It also introduces a concept of thunk
– a function that wraps an expression to delay its evaluation. It is nice and will probably do its job well on the major part of the projects. But as your project grows it becomes difficult to manage and to develop new features. It’s a widespread problem when developers end in callback hell in the large-size project with a large amount of interconnected asynchronous actions. And this is an exact case where Redux-Saga
rocks. Redux-Saga aims to make side-effects management simpler and better using saga
. Redux-Saga is known as a middleware layer in Redux ecosystem. It coordinates and induces asynchronous actions (side-effects). With Middleware
Redux flow diagram looks like this:
To make asynchronous flow easier, Redux-Saga uses ES6 Generators
Generators are functions that can be stopped and continued, instead of executing all expressions in a single step. When you call a generator function, it returns an iterator object. With each call to the iterator’s next()
method, the body of the generator function executes until the next yield expression and then stops. Example of ES Generators: https://gist.github.com/OleksivO/2e1d88bc9f77171444dad262ab759edb Let’s look on an example with asynchronous code: https://gist.github.com/OleksivO/9e3128ccd38cbbfe46937a5490a66f8d
The real project example
As I wrote before, I would like to show you how we refactored action-creators with the saga and made them cleaner, more readable and easy for testing. So, here is a part of reducer and action creators responsible for authorization realized with Redux-Thunk
: https://gist.github.com/OleksivO/e169ebe9ff2586ac7a3fc47337912b79 As you can see, we have 4 actions here: AUTH_START
– set loading property for showing spinner on UI AUTH_SUCCESS
– set the token property with userId when a user is successfully authorized AUTH_FAIL
– set error property if some error occurs during authorization AUTH_LOGOUT
– clear user data from state https://gist.github.com/OleksivO/ab0c362ce439811c1befcd6347063a73 The things are getting more complicated here. So let me describe the logic: – authStart
, authSuccess
, authFail
, logout
– are simple and don’t need to be explained. – auth
– sends a request to a server and handle its response. If the response is successful, stores response data to localStorage for future use, dispatches AUTH_SUCCESS action and calls checkAuthTimeout method. – checkAuthTimeout
– waits until tokens expiration time and dispatches AUTH_LOGOUT action. As you can see, we have some asynchronous code here. As your project grows, more and more logic is applied. So lets see how do following action-creators look like when you move all additional logic to sagas: https://gist.github.com/OleksivO/28c2f5c5a07f488b5ffdc373995046b9 As you could notice, all action-creators became pure functions with a single responsibility to return an action. But I also added a few new actions: AUTH_USER
, AUTH_INITIATE_LOGOUT
, AUTH_CHECK_TIMEOUT
. I added them to separate the actions that should get to Redux-Saga from those that need to get to reducers. For better understanding let look on sagas example: https://gist.github.com/OleksivO/625cd6ee3df6557886c1030bda78b430 In this example, the sagas can be divided into 2 types: 1. saga-watcher
: watchAuthSaga 2. saga-worker
: authUser, checkAuthTimeout, logout These terms refer to a way of organizing the control flow in Redux-Saga. – saga-watcher
is watching for dispatched actions and spawns a new task on every action. You can think about it as another implicit layer in Redux ecosystem. It combines async actions (saga-worker
) into the broader business logic and gives you more flexibility to implement complex solutions. – saga-worker
is responsible for handling all logic required by action and terminating them. saga-watcher
workflow in our example is quite simple. When it triggers an action that should be dispatched, it spawns a new saga-worker
instance using the takeEvery
API. If there are multiple requests, takeEvery
creates multiple instances of the saga-worker
but it does not guarantee that all tasks will terminate in the same order they were started.
Instead of takeEvery
we can use another Redux-Saga API takeLatest
.
As you can guess, takeLatest
, unlike the takeEvery
API, does not create multiple saga-worker
instances for multiple dispatched actions of the same type. It spawns a task on each dispatched action that matches the pattern but automatically cancels any task running previously. Let’s take a closer look on saga-worker
s workflow: https://gist.github.com/OleksivO/171f51eac6ea2b280e6d21338051ac4c Let’s begin with authUser
:
- Dispatches the action to show the spinner.
- Executes an API call.
- Waits for response and if API call succeeds:
- Calculates token expiration date
- Stores user-specific data to the localStorage
- Dispatches
AUTH_SUCCESS
andAUTH_CHECK_TIMEOUT
actions
- In case of failure, dispatches
AUTH_FAIL
action
In this saga-worker
we used two new Redux-Saga API: put
and call
.
The call
method returns the object describing operation we want to execute. – Redux-Saga is able to take care of the call and returns the results to the generator function. – Similar logic is followed by the put
method. Instead of dispatching action inside a generator function, put
returns an object with instructions for our middleware. These returning objects are also called Effects
. Similar to NgRx/Effects. As you could noticed, unlike call
method, put
doesn’t block a flow.
In Redux-Saga there are blocking
and non-blocking
calls.
A blocking call means that the saga yielded an Effect
and will wait for the result of its execution before resuming to the next instruction inside the yielding Generator. A non-blocking call means that the saga will resume immediately after yielding the Effect
. Let’s also look at checkAuthTimeout
workflow: 1. Waits until the token expires 2. Dispatches AUTH_LOGOUT
action In this example, I’ve used another blocking call API delay
. As you can guess from the example this method is very similar to native setTimeout
. It allows us to do the same things as setTimeout
but writing less code. https://gist.github.com/OleksivO/134e11e0b68c574f70f3179fe0ac28f8 In addition to methods shown in this example, Redux-Saga offers many other effects-creators.
How to bind Redux-Saga to a project
Redux-Saga should be registered in your project to be used. https://gist.github.com/OleksivO/0521e956ef86fc6d241c71d8d0af9eb8
Summary
There are no standard solutions to work with side-effects in Redux. Redux-Saga will not improve the performance of your program. But it will make the code more organized and readable. Therefore, it’s up to you to choose which library to use and how to deal with side-effects in your project.
Useful links
Do you like this post? Want to stay updated? Follow us on Twitter or subscribe to our Feed.
See also