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

135
Visualizações
Call API before dispatching action - Redux Toolkit

I am a bit conflicted about this and seem to find no answer. I have a slice with some actions. What I want to do is to fire a request without awaiting it's result (it's a firebase call that should be handled optimistically).

How should I then structure my code around this case? Using createAsyncThunk shouldn't be considered because I am not awaiting anything and dont need to update any local requestStatus variables.

This is what I have right now:

// Component.js (where I do the dispatch)

useEffect(() => dispatch(updateCheckIn(payload)), [])
// CheckInActions.js

import { updateCheckInInDb } from "../../api/checkin"
import { updateCheckInAction } from "../reducers"

export const updateCheckIn = (update) => {
  updateCheckInInDb(update) // make API call
  return updateCheckInAction(update) // return actual reducer action
}
// CheckInReducer.js

const checkInSlice = createSlice({
  name: "checkIn",
  initialState: INITIAL_STATE,
  reducers: {
    updateCheckInAction(state, action) {
      return updateStateViaUpdateApi(state.data, action)
    },
  },
})

export const { updateCheckInAction } = checkInSlice.actions
export default checkInSlice

This works but I feel it is a bit awkward (specially the naming). I would need to call one a updateCheckInAction and the other updateCheckIn. I am a bit new to redux toolkit. Isn't there a more elegant way of doing this?

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

0

The most idiomatic answer here would be hand-write a thunk that kicks off the async request and then dispatches the plain action:

export const updateCheckIn = (update) => {
  return (dispatch) => {
    // make API call
    updateCheckInInDb(update) 
    // dispatch actual action to update state
    dispatch(updateCheckInAction(update)) 
  }
}

// used as
dispatch(updateCheckIn(123))

See https://redux.js.org/usage/writing-logic-thunks for details on what thunks are overall and how to write them.

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