简体   繁体   中英

How do I make two dispatches in redux run in order?

Suppose I have two dispatches I want to fire in order called

dispatch(action1())
dispatch(action2())

Action1 is an action creator created using

createAsyncThunk 

method from redux/toolkit.

Therefore, it uses async... await in the process.

Action2 is a synchronous process.

I want to make

`dispatch(action2())` run only after `action1()` has been dispatched.

How can I achieve this?

I have tried doing

dispatch(action1(), dispatch(action2())

but I have found that dispatching inside of a reducer is an anti-pattern since reducers are pure.

See Unwrapping Result Actions

Thunks may return a value when dispatched. A common use case is to return a promise from the thunk, dispatch the thunk from a component, and then wait for the promise to resolve before doing additional work:

So you can do this:

dispatch(action1()).then(() => {
  dispatch(action2());
})

A simple way might be to let action1 conditionally dispatch action2 where you need it:

const action1 = createAsyncThunk(
  'actions/1',
  async (args, thunkAPI) => {
    const response = await someApi.fetchStuff(args.id);
    if (args.condition) {
        thunkAPI.dispatch(action2());
    }
    return response.data
  }
);

This only works if you don't depend on the reducer having updated the state at that point (usually with this type of scenario it's about the asynchronous work having finished).

If you however also depend on the state update, try the dispatch(action1()).then(...) answer someone else gave.

Another option is to write a "classic" thunk (not using createAsyncThunk ) that coordinates the sequence of action1 and action2.

I personally prefer the last option since bigger thunks can be composed nicely of many smaller thunks.

In case you're wondering, createAsyncThunk is not meant to dispatch another action when returning its result - which would have also solved your problem: https://github.com/reduxjs/redux-toolkit/issues/773

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM