Yaron
Yaron

Reputation: 1965

Awaiting for an async action creator to update the state inside another action creator

I have an action creator that performs an async request and updates the state (using react-redux middleware):

export function requestA() {
  return function (dispatch) {
    dispatch(startRequest())
    return Service.getA().then(
      data => dispatch(receivedA(data)),
      error => console.log("An error occurred.", error)
    )
  }
}

That works fine. Now I want to create another action creator, that will use the requestA() action creator, and will call another async request.

export function requestB() {
  return function (dispatch, getState) {
    dispatch(requestA()) // <--- How to await for this ???
    let A_data = getState().A_data;
    return Service.getB(A_data).then(
      data => dispatch(receivedB(data)),
      error => console.log("An error occurred.", error)
    )
  }
}

Is there a way for me to await for the dispatch(requestA()) to complete before I continue to run the rest of the function? I need the state to be updated before I continue to the next request.

Note I know I could do this by calling the 2 requests in my action creator, but I want to know if I can do it calling the dispatch(requestA()) , as the logic for that is already set.

Upvotes: 0

Views: 88

Answers (1)

Melchia
Melchia

Reputation: 24224

You just need to wait for the call function to finish using await async keywords:

export function requestA() {
  return async function (dispatch) {
    dispatch(startRequest())
    await Service.getA().then(
      data => dispatch(receivedA(data)),
      error => console.log("An error occurred.", error)
    )
  }
}

Upvotes: 1

Related Questions