Tag Archives: async

I wanted to try redux-saga in one of my learning projects but I got confused about how generators are used to do async operations. First I had to understand them so I used generators in my project. Now that I have an overview about them, it’s time to move on redux-saga.

Before going into redux-saga code, I’ll extract relevant usages of react, redux and redux-thunk from my project.

Current implementation with redux-thunk

Dispatch action

CurrentReadingSessionComponent.js

Create action

BookAction.js

fetchBookAction function is the place where redux-thunk is used so that instead of returning a simple action object, it returns another function that receives dispatch function as the first parameter. In this way redux-thunk delays the dispatch of the original action by first getting the data asynchronous and only when data is ready we dispatch another action with the result.

Fetch data

BookApi.js

Update state

BookReducer.js

Create the store

LibraryRouter.js

Connect the store to react component

CurrentReadingSessionComponent.js

Use redux-saga instead of redux-thunk

In order to follow easier the changes, I’ll extract relevant code samples after adding redux-saga in this project. Please note that I’ll focus only in the updates, code that did not change will not be added again.

Create action

BookAction.js

Async calls are not started anymore on action dispatch. fetchBookAction(action) returns a plain action object.

Watch for fetch requests with redux-saga

BookSagas.js

The main change is here, in the new added saga functionality. In redux-thunk version this functionality was implemented with promises chaining. Here we have two generator functions:

  • watchFetchBook uses takeLatest to monitor for FETCH_BOOK action. This is the watcher saga.
  • callFetchBook saga will actually do the work and that’s why is called the worker saga.

Use a root saga

RootSagas.js

This is similar with the root reducer and is needed to start watching for dispatched actions that trigger async calls.

Create the store

LibraryRouter.js

redux-saga middleware replaces corresponding redux-thunk middleware. Here is the place where rootSaga is started.

Conclusion

I see two improvements of using redux-saga instead of redux-thunk:

  • The start of async calls are separated from actions dispatch.
  • Async code is easier to read in this way, at least for me.