I want to introduce a delay in a saga (using redux-saga).
How can I do this?
If redux-saga provides an API, I would also be interested in how to achieve it manually.
function* save({ payload }) {
yield put(pending());
// I want to simply wait (non-blocking) here for say 2 seconds
yield put(complete());
}
You need to do something - as written this will call sleep (returning a promise) and then immediately throw it away! If you yield a call() then redux-saga will wait for the promise to resolve, e.g.: yield call(sleep, 2) . The best solution is in the answer above - using the delay utility function.
Such a powerful & elegant tool as Redux-Saga, a Redux side effect manager, is said to be deprecated, and no longer being maintained, starting from Jan 27, 2021.
Just as in Redux you use action creators to create a plain object describing the action that will get executed by the Store, call creates a plain object describing the function call. The redux-saga middleware takes care of executing the function call and resuming the generator with the resolved response.
In the above example, takeEvery allows multiple fetchData instances to be started concurrently. At a given moment, we can start a new fetchData task while there are still one or more previous fetchData tasks which have not yet terminated.
Redux-sagas has a special effect for this:
delay(ms, [val])
Returns a Promise that will resolve after ms milliseconds with val.
Example:
import { delay, call } from 'redux-saga/effects'
function* someSaga(input) {
yield put(someAction())
yield delay(500)
yield put(anotherAction())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With