Answer the question
In order to leave comments, you need to log in
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})
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
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});
}
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 questionAsk a Question
731 491 924 answers to any question