KUNAL KAMBLE
KUNAL KAMBLE

Reputation: 1

Getting this error "Invariant failed: A state mutation was detected inside a dispatch, in the path: todoReducer.1."

I tried everything like spread operator but nothing works.

Here is my reducer

//state is an array of objects.
const initialState = [
    {taskName: "kkkkk", isEdit: false},
]
export const todoReducer = (state=initialState, action) =>{
    switch(action.type){
        case 'add'  :   
            
            const temp=
            {
                taskName: action.payload.taskName,
                isEdit: action.payload.isEdit
            }
            state.push(temp);
            return {state}
       default: return state
    }
}

Upvotes: 0

Views: 673

Answers (1)

phry
phry

Reputation: 44146

The error message indicates that you are using Redux Toolkit - that is very good. The problem is that you are not using createSlice or createReducer and outside of those, in Redux you are never allowed to assign something to old state properties with = or call something like .push as it would modify the existing state.

Use createSlice instead:

const initialState = [
    {taskName: "kkkkk", isEdit: false},
]
const slice = createSlice({
  name: 'todos',
  reducers: {
    add(state, action) {
      state.push(action.payload)
    }
  }
})
export const todoReducer = slice.reducer;
// this exports the auto-generated `add` action creator.
export const { add } = slice.actions;

Since the tutorial you are currently following seems to be incorporating both modern and completely outdated practices, I would highly recommend you to read the official Redux Tutorial instead, which shows modern concepts.

Upvotes: 2

Related Questions