6

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.

Adolfo
  • 1,315
  • 2
  • 14
  • 22

2 Answers2

14

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.

markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Hey Mark! I am trying to reset the store made using `configureStore`. I haven't found any answers on that. Can you please drop a comment here? Thanks! – Piyush Aggarwal Feb 21 '23 at 17:31
  • @PiyushAggarwal what do you mean by "reset the store", exactly? – markerikson Feb 22 '23 at 04:10
  • Like if I had refreshed the page. I need all slices to have the initial state on logout without refresh. I know how to do it for a single slice. But I am unable to do it for all the other slices at once. – Piyush Aggarwal Feb 22 '23 at 10:37
  • @PiyushAggarwal that's really an entirely separate question, unrelated to this one :) Can you post that separately, with example code? – markerikson Feb 22 '23 at 14:47
  • I have added a question. Thank you for the help. https://stackoverflow.com/questions/75608012/how-to-reset-to-initial-state-in-all-slices-in-redux-store-setup-using-redux-too – Piyush Aggarwal Mar 01 '23 at 19:15
0
resetState: (state, action) => {
      Object.assign(state, action.payload)
 },
Behzad Jafari
  • 110
  • 1
  • 6
  • 6
    Please refrain from writing a code snippet as an answer. Please take a look at [SO documentation on how to write an answer](https://stackoverflow.com/help/how-to-answer) to learn how it's done. – guzmonne Jun 02 '21 at 14:52