Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get redux-saga to wait for two actions to happen at least once in any order?

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?

like image 544
momo Avatar asked Jun 07 '17 03:06

momo


People also ask

How do you wait in Redux Saga?

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.

Is Redux Saga multithreaded?

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.

What does fork do in Redux Saga?

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.

Is Redux Saga obsolete?

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.


1 Answers

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())
}
like image 197
erikvold Avatar answered Oct 05 '22 15:10

erikvold