1. The story – saga

What is Redux-Saga, and what pain points does it address?

Redux-saga is a library for managing Side effects (Side effects, such as asynchronously fetching data, accessing browser caches, etc.) in applications, with the goal of making Side effects management easier, execution more efficient, testing simpler, and handling failures easier.

What is a saga

  • Saga is a type of Middleware that works between actions and reducer.
  • A saga is like a single thread in an application that is solely responsible for handling side effects

What is the Effect

In the redux-Saga world, Sagas are implemented using Generator functions. We yield pure JavaScript objects from the Generator to express Saga logic. We call those objects effects. An Effect is a simple object that contains some information for middleware to explain execution. You can think of effects as instructions sent to middleware to perform certain actions (call some asynchronous function, initiate an action to a store, etc.)

What process does Redux-Saga go through when executing dispatch(Action)

  • Saga needs a global listener (Watcher Saga), which is used to monitor the actions issued by the component, forward the monitored actions to the corresponding receiver (Worker Saga), and then perform specific tasks by the receiver. After the task is executed, Another action is sent and sent to reducer to modify state. Therefore, attention must be paid to the following: The action monitored by Watcher saga cannot be the same as the action issued by the corresponding worker saga, otherwise an infinite loop will occur
  • In Saga, both global listeners and receivers use Generator functions and some of saga’s own auxiliary functions to control the entire process
  • The whole process can be simply described as

Component - > Action1 - > Watcher Saga - > Worker Saga - > Action2 - > Reducer - > Component

  • Compared with Thunk, saga has one more action, because saga describes the triggering (Watcher Saga) and the execution (worker saga) of the business separately
  • Just create an object to indicate to the Middleware that we need to initiate some actions, and then let the Middleware perform actual dispatches. This way we can test Generator dispatch in the same way: just check the Effect after yield and make sure it contains the correct instruction.
  • Redux-saga provides another function for this, put, which creates the Dispatch Effect.