API Reference in Redux-saga

Tram Ho

Introduce

In today’s article I will introduce API Reference in Redux-saga, how to create Middleware API and introduce basic Effect creators.

Middleware API

createSagaMiddleware (options)

Create a Redux middleware and connect Saga to the Redux store.

options: Object- A list of options for moving to middleware. The currently supported options are:

  • context: Object – initial value of the saga context.
  • sagaMonitor: SagaMonitor – If provided with a Saga Monitor, the middleware will distribute monitoring events to the monitor.
  • onError: (error: Error, {sagaStack: string}) – If provided, the middleware will call it with undetected errors from Sagas. Useful for sending unsaved exceptions to error tracking services.
  • effectMiddlewares: Function [] – allows you to block all effects, solve them by yourself and move on to the next middleware.

For example

File configureStore.js

Above I will create a configureStore function that will enhance the Store with a new runSaga method. Then in my main module, I will use the method to start the application’s Saga root.

main.js

Note

  • The saga must be a function that returns a Generator Object. The middleware will then repeat Generator and perform all yielded Effect.
  • saga can also start other sagas using different effects provided by the library.
  • In the first iteration, the middleware calls the next () method to get the next Effect. The middleware then executes the yielded Effect as specified by the Effects API below. Meanwhile, the Generator will be stopped until the effect execution has finished. Upon receiving the execution result, the middleware calls next (result) on the Generator through the results retrieved as an argument. This process is repeated until the Generator finishes normally or by giving some errors.
  • If execution results in an error (as specified by each Effect creator), the Generator’s throw (error) method is called instead. If the Generator function defines a try / catch around the current yield command, then the catch block will be called by the Generator runtime below. The runtime will also call any corresponding last block.
  • In the event that Saga is canceled (either manually or using the provided Effects), the middleware will call the Generator’s return () method. This will cause the Generator to skip directly to the last block.

Effect creators

take

Creating an Effect description instructs the middleware to wait for a specified action on the Store. The generator pauses until a pattern matching action is sent.

The yield take (pattern) result is an action object that is sent.

The pattern is explained using the following rules:

  • If take is called without an argument or ' * ' all actions sent are matched (e.g. take () will match all actions).
  • If it’s a function, the action is matched if the pattern (action) is correct (for example, take (action => action.entities) will match all actions with the field (truthy) entities.)
  • If String, action is matched if action.type === pattern (e.g. take (INCREMENT_ASYNC)
  • If an array, each item in the array matches the aforementioned rules, so a mixed array of strings and function predicates is supported. The most common use case is an array of strings, so it action.type matches all items in the array (e.g. take ([INCREMENT, DECREMENT]) and will match actions of type INCREMENT or DECREMENT).

takeMaybe

Similar to take but not automatically terminating Saga on an END action. Instead, all Sagas that are blocked on a Take Effect will get the END object.

takeEvery

Spawn a saga on each action sent to the Store in accordance with the pattern.

  • pattern: String | Array | Function
  • saga: Function
  • args: Array <any> – argument passed to the start task. takeEvery will add the incoming action to the argument list.

In the following example, we create a fetchUser basic task. We use takeEvery to start a new task fetchUser on every USER_REQUESTED action being sent:

takeLatest

Forks one saga per action is sent to the Store matching the pattern. And automatically cancel any previous task saga that has started earlier if it is still running.

Each time an action is sent to the Store. And if this action matches the pattern, takeLatest starts a new task saga in the background. If a task saga has been started before (on the last action sent before the actual action) and if this task is still running, the task will be canceled.

  • pattern: String | Array | Function
  • saga: Function
  • args: Array <any> – argument passed to the starting task. takeLatest will add a new action to the argument list.

In the following example, we create a basic task fetchUser. We use takeLatest to start a new fetchUser task on every USER_REQUESTED action that is sent. Because takeLatest cancels any pending tasks that have started before, we guarantee that if the user activates multiple actions of USER_REQUESTED in a row quickly, we will only end with the latest action.

put

Creating an Effect description instructs the middleware to schedule sending an action to the store. This dispatch may not be instant because other tasks may be in the front of the saga tasks queue or still in progress.

However, it is expected that the store will be updated in the current stack frame, unless you have other Redux middlewares with asynchronous threads that delay the action transmission.

call

Create an Effect description that instructs the middleware to call fn with args as an argument.

  • fn: Function – The Generator function or normal function returns the Promise as a result or any other value.
  • args: Array <any> – An array of values ​​passed as an argument to fn

select

Create an effect that instructs the middleware to call the selector provided on the current Store state (ie return the result of the selector (getState (), … args)).

  • selector: Function- a function (state, … args) => args. It takes the current state and arbitrarily a number of arguments and returns a slice of the current Store state.
  • args: Array <any> – optional arguments passed to the selector in addition to getState.
  • If select is called without an argument (i.e. yield select ()) then the effect is resolved with the entire state (same result of a getState () call).

retry (maxTries, delay, fn, … args)

Create an Effect description that instructs the middleware to call fn with args as an argument. In case of failure it will try to make another call after a delay of milliseconds, if a number of attempts <maxTries.

  • maxTries: Number – the maximum number of calls.
  • delay: Number- the length of a time window in milliseconds between fn calls.
  • fn: Function – The Generator function or normal function returns the Promise as a result or any other value.
  • args: Array <any> – An array of values ​​passed as an argument to fn.

In the following example, we create a basic task retrySaga. We use retry to try to fetch the API 3 times with a 10 second interval. If the request fails the first time the retry will call the request again while the calls are counted less than 3.

Effect combinators

race (effects)

Create an Effect description to guide the middleware to run a Race between many Effects (this is similar to how to do Promise.race ([…])).

effects: Object – a dictionary Object of the form {label: effect, …}

The following example runs a race between two effects:

  1. A call to a fetchUsers function returns a Promise.
  2. A final CANCEL_FETCH action can be sent on the Store.

If the call (fetchUsers) resolves (or declines) first, the result of the race will be an object with an object with a unique key {response: result} in which the result resolved is fetchUsers.

If an action of type CANCEL_FETCH is submitted on the Store before fetchUsers completes, the result will be a single lock object {cancel: action}, where the action is the action to be sent.

all ([… effects]) (aka parallel effects)

Creating an Effect description instructs the middleware to run in parallel with multiple Effects and wait for them to complete.

The following example runs two blocking calls in parallel:

all (effects)

Like all ([… effects]) but allows you to pass in a dictionary object of effects with labels, just like race (effects).

effects: Object – a dictionary Objec has the form {label: effect, …}

The following example runs two blocking calls in parallel:

External API

runSaga (options, saga, … args)

Lets start sagas outside of the Redux middleware environment. Useful if you want to connect Saga to external input / output, in addition to storage actions.

runSaga returns a Task object. Like returning from a fork effect.

options: Object – currently supported options are:

  • channel- see documentation for the channel
    • dispatch (output): Function- is used to perform put effects.
    • output: any- argument provided by Saga for put Effect.
    • getState (): Function- is used to perform select and getState effects.
    • sagaMonitor: SagaMonitor
    • onError: Function
    • context: {}
    • effectMiddlewares: Function []
  • saga: Function
  • args: Array <any> – the arguments provided for the saga.

The {channel, dispatch} is used to fully implement take and put Effects. This determines the Input / Output interface of Saga.

The channel is used to perform take (PATTERN) effects. Every time something is posted on the channel, it will notify all internal listeners pending. If Saga is blocked on the take effect and if the take pattern matches the current input, Saga will continue with that input.

Dispatch is used to perform put effects. Whenever Saga issues a yield put (output), the dispatch is called with the output.

References

Please refer here: https://redux-saga.js.org/docs/api/

Share the news now

Source : Viblo