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

1

19

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?

Spiritualize answered 7/6, 2017 at 3:44 Comment(0)
B
35

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())
}
Bunyip answered 9/7, 2017 at 18:53 Comment(4)
How would you do it if any of these 2 was required?Commuter
post another question.Bunyip
@Commuter use the race effect instead of allStenophagous
You can const firstAction = yield take([action1, action2])Pantheas

© 2022 - 2024 — McMap. All rights reserved.