Omortis
Omortis

Reputation: 1530

passing an async response "through" a thunk

Is it possible to pass an async "response" through a thunk? Given the action creator below:

export function emitLoadPlot(json_req) {
  return function (dispatch) {
    axios.post(URI, {
      json_req
    })
    // .then(() => dispatch(
    //   emitTxRxAlert("yellow", "Received plot from server")
    // ))
    .then((response) => dispatch({
      type: EMIT_PLOT_DATA_REQ,
      payload: response
    }))
    .then(() => dispatch(
      emitTxRxAlert("green", "Loaded plot model")
    ))
    .then(() => dispatch({
      type: EMIT_LOAD_PLOT
    }))
    .then(() => dispatch({
      type: EMIT_VIEW_STATUS
    }))
  };
}

If I uncomment the Alert dispatch the response never makes it to where it's needed. Makes sense. Some of these calls (and the manipulation on the client end) take a long time to complete and I'd like to interleave client UI alerts (say) between when the async request returns in the browser and when it loads into the redux store. On this slow laptop the network request takes a lot less time than processing the response.

Is there any way for me to pass the response (or the reference to the response) through the first thunk above?

Upvotes: 0

Views: 22

Answers (1)

SLaks
SLaks

Reputation: 887449

Calling then() returns a promise of the result of your callback.

Your callback returns whatever dispatch() returns, which is not the value you want.

Instead, you need to return the original value:

.then(response => {
  dispatch(...);
  return response;
})

Upvotes: 1

Related Questions