How to reset a redux slice state with Redux Toolkit (RTK)

Viewed 3334

I am trying to reset state via a redux action called resetState, where I assign the state to the initialState variable, however this does not work.

const initialState = {
  someArray: [],
  someEvents: {}
}

const stateSlice = createSlice({
  name: "someState",
  initialState,
  reducers: {
    ...someActions,
    resetState: (state, action) => {
      // THIS DOES NOT WORK
      state = initialState
    },
    resetState2: (state, action) => {
      // THIS WORKS!!!!
      return initialState
    },
});

When I return the initialState, the state resets properly, but assigning it to initialState does not.

2 Answers

Assigning state = anything is not correct, regardless of whether you're using Redux Toolkit or writing the reducers by hand. All that does is point the local state variable to a different reference.

RTK's createSlice uses Immer inside. Immer primarily works by tracking mutations to a wrapped value, such as state.someField = 123. Immer also allows you to return an entirely new state you've constructed yourself.

So, in this case, what you want is return initialState to return a new value and force Immer to replace the old one.

resetState: (state, action) => {
      Object.assign(state, action.payload)
 },
Related