Redux saga noob here.
I need to create a saga that loads the initial state for the redux store from my API server.
This involves using two async sagas: getCurrentUser
and getGroups
.
I need to issue these ajax requests in parallel and wait for the GET_CURRENT_USER_SUCCESS
and GET_GROUPS_SUCCESS
actions before issuing the pageReady
action which tells the UI it's time to render the react components.
I came up with a hacky solution:
function * loadInitialState () {
yield fork(getCurrentUser)
yield fork(getGroups)
while (true) {
yield take([
actions.GET_GROUPS_SUCCESS,
actions.GET_CURRENT_USER_SUCCESS
])
yield take([
actions.GET_GROUPS_SUCCESS,
actions.GET_CURRENT_USER_SUCCESS
])
yield put(actions.pageReady())
}
}
The problem with this code is that if for some reason GET_GROUPS_SUCCESS
is issued twice, the pageReady
action will be called to early.
How can I get redux saga to wait for GET_GROUPS_SUCCESS
and GET_CURRENT_USER_SUCCESS
to happen at least once in any order?
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.
Redux-Saga has introduced a way of multi-tasking. Multi-tasking in the sense, that you can start a lot of parallel tasks -which of them can be blocked at any time — without blocking the whole application program flow.
Redux-Saga is a very powerful library for handling side effects in an app. It has a fork model that allows you to run some tasks in a parallel fashion.
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.
I think you want the all
effect
function * loadInitialState () {
// start loading state...
yield all([
take(actions.GET_GROUPS_SUCCESS)
take(actions.GET_CURRENT_USER_SUCCESS)
]);
yield put(actions.pageReady())
}
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