Using Redux-saga with React

Redux-saga is a library used to improve and simplify side-effects implementation in React Redux applications. Some of them are asynchronous actions like data load or access to the browser cache.

Think of saga as a separate thread in your app that handles side-effects. Redux-saga can be called as a middleware as simple redux actions can start, stop and cancel this thread in the main application. It has access to the full redux state and it can dispatch redux actions.

Asynchronous threads look like standard JavaScript code that is synchronous. The library sticks to the ES6 concept that is generators for making these asynchronous threads easy to write, read and test. You’ve probably used redux-thunk before processing some data extracts. With redux-saga, you don’t get into the callback hell as you can easily test your asynchronous actions while your actions remain clear.

Where to start

$ npm install –save redux-saga

or

$ yarn add redux-saga

Code examples

Let’s consider having an interface for retrieving some user data from a remote server after clicking on a button.

The components are dispatching an action as a simple Store object. We’ll create saga that will listen to all USER_FETCH_REQUESTED actions triggers API calls for retrieving user data.

sagas.js

We start “fetchUser” for every dispatched `USER_FETCH_REQUESTED` action. It helps us receive user data simultaneously.

You can use “takeLatest” as an alternative. It doesn’t allow retrieving data from several users. If “USER_FETCH_REQUESTED” is dispatched while the previous request is awaiting the response, this request will be canceled, the last request will be handled.

We should connect saga to the Redux Store with the help of redux-saga middleware to start it.

main.js

We create saga middleware.

We mount it to the Store.

We start saga.

And we render the application.

Using UMD builds in a browser

There’s a umd build available in dist/ directory. redux-saga is available as ReduxSaga in window object while using the umd builds. This build is helpful if you are not using Webpack or Browserify.

If your browser doesn’t support ES2015 generators, you should enable a working polyfill that should be imported to redux-saga:

Building examples from the source files

Counterexamples

counter-vanilla

It’s a demo using JavaScript and UMD builds. You can find all the sources in index.html. Open this file in your browser. Your browser should support Generators. The latest versions of Chrome, Edge or Firefox won’t fit.

counter

It’s a demo using webpack and takeEvery high-level API.

Cancellable-counter

Here’s a low-level API for displaying the task cancellation.

Shopping Cart

Async example