18

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?

erikvold
  • 15,988
  • 11
  • 54
  • 98
momo
  • 975
  • 1
  • 8
  • 8

1 Answers1

34

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())
}
erikvold
  • 15,988
  • 11
  • 54
  • 98