How to use object spread reduxjs/toolkit

Viewed 1317

I'm trying to implement @reduxjs/toolkit into my project and currently I'm facing problem with using spread operator

const initialState: AlertState = {
  message: '',
  open: false,
  type: 'success',
};

const alertReducer = createSlice({
  name: 'alert',
  initialState,
  reducers: {
    setAlert(state, action: PayloadAction<Partial<AlertState>>) {
      state = {
        ...state,
        ...action.payload,
      };
    },
  },
});

When I'm assigning state to new object my store doesn't update. But if I change reducer to code

state.message = action.payload.message || state.message;
state.open = action.payload.open || state.open;

But that's not very handy. So is there way to use spread operator?

1 Answers

In this case, you should return the new object from the function instead:

    setAlert(state, action: PayloadAction<Partial<AlertState>>) {
      return {
        ...state,
        ...action.payload,
      };
    },

You can examine more examples in the docs. Also, be aware of this rule:

you need to ensure that you either mutate the state argument or return a new state, but not both.

Related