简体   繁体   中英

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?

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.

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