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.

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:

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:
Let’s look on an example with asynchronous code:

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:

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 authorizationAUTH_LOGOUT - clear user data from state

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:

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:

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-workers workflow:

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 and AUTH_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.

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.
In addition to methods shown in this example, Redux-Saga offers many other effects-creators.

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.