Add item to nested array in redux-toolkit

Viewed 1888

Redux Toolkit is giving me mutation errors when trying to update state on a nested array, which I thought it was using immer to get around this and simplify the reducers.

My store looks like :

state -> forms -> sections

I want to add a section to an existing form.

My action takes a form and a section

the reducer looks like

let intialState={
    forms:[]
}

const FormsReducer = createReducer(intialState, {
    ADD_SECTION: (state, action) => {
        const index = state.forms.findIndex(f => f.id === action.form.id);
        state.forms[index].__formSections.push(action.payload);
        },

A state mutation was detected inside a dispatch, in the path: FormsReducer.forms.0.__formSections.0

Yet according to the redux-toolkit documentation is should be possible to "write "mutative" immutable update logic"...

What am I doing wrong and how can I fix it?

1 Answers

If you return it without mutating from reducer the error will not occur


const FormsReducer = createReducer(intialState, {
    ADD_SECTION: (state, action) => {
        const newstate = {...state}
        const index = newstate.forms.findIndex(f => f.id === action.form.id);
        newstate.forms[index].__formSections.push(action.payload);
        return newstate 
},
Related