Redux Toolkit caseReducers skip prepare callback in reducer function

1.7k Views Asked by At

I have a reducer for adding comment as follow

addComment: {
  reducer: (state,action)=>{
    const { newId, comment } = action.payload
    console.log(newId)
    // functions that create an new comment entry with the newID and update state
  },
  prepare: (input) =>{
    return {
      payload: {
        ...input,
        newId: nanoid(),
      }
  }
}

If I call dispatch within my app as follow, the console.log shows the id generated by nanoid(). So far so good.

dispatch(addComment({comment: comment}))

However if I call the reducer within another reducer using the caseReducers, console.log returns undefined

commentSlice.caseReducers.addComment(state,{
  payload: {
    comment : comment
  }
})

How do I get the prepare callback to run when using caseReducers.

1

There are 1 best solutions below

1
On

Based on the docs it looks like if you are to invoke using the caseReducer way, you need to include the "type":

const slice = createSlice({
  name: 'test',
  initialState: 0,
  reducers: {
    increment: (state, action: PayloadAction<number>) => state + action.payload,
  },
})
// now available:
slice.actions.increment(2)
// also available:
slice.caseReducers.increment(0, { type: 'increment', payload: 5 })