const initialState: TaskState = {
tasks: [],
};
export const taskSlice = createSlice({
name: "task",
initialState,
reducers: {
addTask: (state, action: PayloadAction<localTask>) => {
state.tasks.push(action.payload);
},
removeTask: (state, action: PayloadAction<localTask>) => {
state.tasks = state.tasks.filter((item) => item.id !== action.payload.id);
},
updateTask: (state, action: PayloadAction<localTask>) => {
state.tasks.map((task) => {
if (task.id === action.payload.id) {
task.title = action.payload.title;
task.description = action.payload.description;
}
});
},
},
});
This slice gives a warning when updateTask is dispatched:
Warning: An unhandled error was caught from submitForm() [Error: Invariant failed: A state mutation was detected between dispatches, in the path 'task.tasks.3.description'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)]
Can you please help me to get this issue fixed? Thanks in advance.
I tried several ways including returning the new state object from the reducer function as well without any luck.
CodePudding user response:
This is caused by a mutation of your Redux state outside of a reducer - probably somewhere in your component code.
That could look like
const task = useSelector(state => state.tasks.task[id])
// in an event handler
task.description = newValue // this line actually modifies your Redux store, because `task` is part of your store!
dispatch(updateTask(task))
instead you should do
const task = useSelector(state => state.tasks.task[id])
// in an event handler
dispatch(updateTask({ id: task.id, description: newValue }))