'Redux, Redux Toolkit how to wait until dispatch is finished

guys

Like in the subject is there a solution to wait until dispatch action is finished and then dispatch another?

Do I need thunk?

dispatch(someAction());

when someAction is finished dispatch anotherAction()

dispatch(anotherAction());


Solution 1:[1]

It really depends on the action. Normal non-thunk actions are synchronous, so in the next line after the dispatch, the first action will already be 100% handled. If you are dispatching thunk actions there, you can either await or .then(..) the value that is returned by dispatch.

Solution 2:[2]

To elaborate on the idea of @phry. I use redux-toolkit and have this as an example thunk:

export const EXAMPLE_THUNK = createAsyncThunk(
  "group/event/example_thunk",
  async () => {
    // Just resolves after 2 seconds.
    return await new Promise((resolve) => setTimeout(resolve, 2000));
  }
);

To dispatch another action after the first dispatch, you can simply await the first dispatch. In my example I updated the loading state.

Although this example works, I am not 100% sure this is the best design pattern out there. Many examples I have seen is updating the state is some dispatch has been resolved! Personally I think this is a more clear way of writing my code

 const handleChangeStatus = async () => {
    setIsLoading(true);
    await dispatch(EXAMPLE_THUNK())
    // Or dispatch something else. 
    setIsLoading(false);
  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 phry
Solution 2 Wiezalditzijn