DEV Community

Discussion on: Writing modern Redux in 2020 - The powerful createSlice

Collapse
 
markerikson profile image
Mark Erikson

Very nice!

One additional bit: as with createAction, you can define a "prepare callback" function that can be used to turn multiple arguments into the payload field, generate unique IDs, or whatever other consistent prep work needs to be done for the action:

const todosSlice = createSlice({
  name: 'todos',
  initialState: [], 
  reducers: {
    addTodo: {
      prepare(text) {
        const id = uuid();
        return {payload: {id, text}};
      },
      reducer(state, action) {
        const { id, text } = action.payload
        state.push({ id, text, completed: false })
      }
    }
  }
})