Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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());
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda