Skip to content

Commit 0f33780

Browse files
committed
todo with reducer
1 parent 08d4b71 commit 0f33780

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

src/App.js

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,38 @@ const filterReducer = (state, action) => {
3232
}
3333
};
3434

35+
const todoReducer = (state, action) => {
36+
switch (action.type) {
37+
case 'DO_TODO':
38+
return state.map(todo => {
39+
if (todo.id === action.id) {
40+
return { ...todo, complete: true };
41+
} else {
42+
return todo;
43+
}
44+
});
45+
case 'UNDO_TODO':
46+
return state.map(todo => {
47+
if (todo.id === action.id) {
48+
return { ...todo, complete: false };
49+
} else {
50+
return todo;
51+
}
52+
});
53+
case 'ADD_TODO':
54+
return state.concat({
55+
task: action.task,
56+
id: uuid(),
57+
complete: false,
58+
});
59+
default:
60+
throw new Error();
61+
}
62+
};
63+
3564
const App = () => {
3665
const [filter, dispatchFilter] = useReducer(filterReducer, 'ALL');
37-
const [todos, setTodos] = useState(initalTodos);
66+
const [todos, dispatchTodos] = useReducer(todoReducer, initalTodos);
3867
const [task, setTask] = useState('');
3968

4069
const handleShowAll = () => {
@@ -65,16 +94,11 @@ const App = () => {
6594
return false;
6695
});
6796

68-
const handleChangeCheckbox = id => {
69-
setTodos(
70-
todos.map(todo => {
71-
if (todo.id === id) {
72-
return { ...todo, complete: !todo.complete };
73-
} else {
74-
return todo;
75-
}
76-
})
77-
);
97+
const handleChangeCheckbox = todo => {
98+
dispatchTodos({
99+
type: todo.complete ? 'UNDO_TODO' : 'DO_TODO',
100+
id: todo.id,
101+
});
78102
};
79103

80104
const handleChangeInput = event => {
@@ -83,7 +107,7 @@ const App = () => {
83107

84108
const handleSubmit = event => {
85109
if (task) {
86-
setTodos(todos.concat({ id: uuid(), task, complete: false }));
110+
dispatchTodos({ type: 'ADD_TODO', task });
87111
}
88112

89113
setTask('');
@@ -112,7 +136,7 @@ const App = () => {
112136
<input
113137
type="checkbox"
114138
checked={todo.complete}
115-
onChange={() => handleChangeCheckbox(todo.id)}
139+
onChange={() => handleChangeCheckbox(todo)}
116140
/>
117141
{todo.task}
118142
</label>

0 commit comments

Comments
 (0)