D
D
Danil Chekalin2018-07-12 23:54:40
React
Danil Chekalin, 2018-07-12 23:54:40

How to wait for a dispatch to complete with an async action in redux?

There is a code:

dispatch({type: Constant.SOME_OPERATION_1})
dispatch(createAccount())
dispatch({type: Constant.SOME_OPERATION_2})

`createAccount` was an async action and looked something like this:
export const createAccount = () => async (dispatch) => {
  // request api
  // dispatch({type: SMTH})
  // another request api
  // dispatch({type: SMTH2})
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-13
@dakiesse

If you want to wait for asynchronous calls in asynchronous functions, then they must be done using the await keyword. Calls to dispatch passing regular action objects are executed synchronously.

const someCall = () => async dispatch() => {
  dispatch({type: Constant.SOME_OPERATION_1});
  await dispatch(createAccount());
  dispatch({type: Constant.SOME_OPERATION_2});
};

export const createAccount = () => async (dispatch) => {
  await request api;
  dispatch({type: SMTH});
  await another request api;
  dispatch({type: SMTH2});
}

You can also use try/catch to handle failed server responses:
export const createAccount = () => async (dispatch) => {
  try {
    await request api;
    dispatch({type: SMTH});
    await another request api;
    dispatch({type: SMTH2});
  catch (e) {
    // handle error here
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question