Redux Saga – How to make real good things with generators
What Is Redux Saga?
Redux Saga is a library that’s used as a middleware for Redux. A Redux middleware is code that intercepts actions coming into the store via the dispatch() method and can take perform tasks based on the action received. Sagas watch all actions (observer/watcher) that are dispatched from the store. Before the action is passed on to the props, the other function (worker) will process what to do with the action in asynchronous flow.
Redux Saga uses an ES6 feature called Generators, which allows you to write asynchronous code. It’s important to know how the flow of Redux Saga works, specifically what happens with the Sagas (Generator Functions). Generator Functions allow queueing operations using yield, making it asynchronous
.
Why Use Redux Saga?
Redux Saga helps Redux with managing application side effects. This makes your code more efficient to execute, easier to test, and allows for better error handling.
1. Better Handling of Actions And Asynchronous Operations
2. Easier to Read with No Callback Hell
3. Better Error Handling
4. Manages Complex Flow
5. Declarative Effects
6. Easy to Test
Thunk and Saga
There are two common ways of dealing with side effects in Redux applications. Thunk is a function that already has everything it needs to execute. In Redux actions are defined with simple objects. And the main benefit of thunk that it allows to send a function instead. So you already able to write some logic to execute immediately and dispatch other actions.
Let’s begin from initial steps and add it to the project with npm install redux-saga.
Let’s define our fetchDataSaga with some comments and explanations: