Search code examples
reduxreact-reduxredux-toolkit

Is it possible to reassign the whole state in a slice reducer (using Redux ToolKit)?


I am using Redux Toolkit's createSlice(). And trying to create a reducer that populates data from an external source into the redux state. I'm trying to update the whole state by passing in an object in the action payload:

.
    reducers: {
        populateData: (state, action) => {
            state = action.payload
        }
.

but it will only work if I create a reducer for each object key. Is there a way to do this all at once?


Solution

  • This is a common misunderstanding, and I actually just wrote a new "Writing Reducers with Immer" docs page yesterday that answers this question. Quoting that:

    A common mistake is to try assigning state = someValue directly. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.

    Instead, you want: return action.payload, which will replace the existing state entirely.