Search code examples
javascriptreactjsreduxredux-toolkit

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?


Solution

  • 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.