Created
August 29, 2025 01:39
-
-
Save pierodev0/3c8668e034489c074d139f1047a9e952 to your computer and use it in GitHub Desktop.
Template reducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // types.ts | |
| export type Todo = { | |
| id: string; | |
| text: string; | |
| completed: boolean; | |
| }; | |
| export type TodoActions = | |
| | { | |
| type: 'add-todo'; | |
| payload: { text: string }; | |
| } | |
| | { | |
| type: 'toggle-todo'; | |
| payload: { id: Todo['id'] }; | |
| } | |
| | { | |
| type: 'remove-todo'; | |
| payload: { id: Todo['id'] }; | |
| } | |
| | { | |
| type: 'clear-completed'; | |
| }; | |
| export type TodoState = { | |
| todos: Todo[]; | |
| }; | |
| export const initialState: TodoState = { | |
| todos: [], | |
| }; | |
| // Reducer | |
| export const todoReducer = ( | |
| state: TodoState = initialState, | |
| action: TodoActions | |
| ): TodoState => { | |
| if (action.type === 'add-todo') { | |
| const newTodo: Todo = { | |
| id: crypto.randomUUID(), | |
| text: action.payload.text, | |
| completed: false, | |
| }; | |
| return { | |
| ...state, | |
| todos: [...state.todos, newTodo], | |
| }; | |
| } | |
| if (action.type === 'toggle-todo') { | |
| const updatedTodos = state.todos.map((todo) => | |
| todo.id === action.payload.id | |
| ? { ...todo, completed: !todo.completed } | |
| : todo | |
| ); | |
| return { | |
| ...state, | |
| todos: updatedTodos, | |
| }; | |
| } | |
| if (action.type === 'remove-todo') { | |
| const updatedTodos = state.todos.filter( | |
| (todo) => todo.id !== action.payload.id | |
| ); | |
| return { | |
| ...state, | |
| todos: updatedTodos, | |
| }; | |
| } | |
| if (action.type === 'clear-completed') { | |
| const updatedTodos = state.todos.filter((todo) => !todo.completed); | |
| return { | |
| ...state, | |
| todos: updatedTodos, | |
| }; | |
| } | |
| return state; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment