I’m learning useReducer. I defined a Todo class and passed an instance to action.payload, but the toggle action did not work with immer in strict mode. When I changed the class to a type alias, it worked.
My reduce function :
export function todoReducer(todos:Todo[], action: Action<Todo>):Todo[] {
switch (action.type) {
case ActionTypes.ADD_TODO:
return [...todos, action.payload as Todo];
case ActionTypes.DELETE_TODO:
return todos.filter(todo => todo.id !== action.payload!.id);
case TodoActionTypes.TOGGLE_TODO:
return produce(todos, (draft:Todo[]) => {
const todo = draft.find((todo => todo.id === (action.payload as number)))!
todo.isComplete = !todo.isComplete;
console.log(todo.isComplete);
});
default:
return todos;
}
}
The class definition:
export default class Todo {
id: number;
title: string;
isComplete: boolean;
constructor(title: string) {
this.id = Date.now();
this.title = title;
this.isComplete = false;
}
}
The type definition:
export type Todo = {
id: number;
title: string;
isComplete: boolean;
};
The class instance did work without immer
case ActionTypes.TOGGLE_TODO:
return todos.map(todo => {
if (todo.id === action.payload!.id) {
return {...todo, isComplete:!action.payload!.isComplete}
}
return todo;
});