Skip to content

Commit 57af5f2

Browse files
author
Duc Le
committed
Handle onRemoveTodo
1 parent f61da2a commit 57af5f2

File tree

3 files changed

+26
-8
lines changed

3 files changed

+26
-8
lines changed

src/Todo.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ const Todo = () => {
3939
saveTodoItemsToLocalStorage('todo', newTodoItems)
4040
}, [todoItems]) // Dependencies list for useCallback
4141

42+
const removeTodoHandler = useCallback(id => {
43+
// Filter out the todoItem which is about to be removed
44+
const newTodoItems = todoItems.filter(todoItem => todoItem.id !== id)
45+
46+
// Update todoItems state
47+
setTodoItems(newTodoItems)
48+
49+
// Save to localStorage
50+
saveTodoItemsToLocalStorage('todo', newTodoItems)
51+
}, [todoItems])
52+
4253
return (
4354
<div className="todo">
4455
<h1>Todo</h1>
@@ -49,6 +60,7 @@ const Todo = () => {
4960

5061
<TodoList
5162
todoItems={todoItems} // Passing todoItems to TodoList
63+
onRemoveTodo={removeTodoHandler} // Passing addTodoHandler to TodoList
5264
/>
5365
</div>
5466
);

src/components/TodoItem.js

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1-
import React from 'react';
1+
import React, { useCallback } from 'react';
22

3-
const TodoItem = ({ todo }) => (
4-
// TODO: we'll have more things to work with this components later.
5-
<li>
6-
{todo}
7-
</li>
8-
);
3+
const TodoItem = ({ todo, id, onRemoveTodo }) => {
4+
const removeTodoHandler = useCallback(() => onRemoveTodo(id), [id, onRemoveTodo])
5+
6+
return (
7+
<li>
8+
<span>{todo}</span>
9+
<button onClick={removeTodoHandler}>Remove</button>
10+
</li>
11+
)
12+
};
913

1014
export default TodoItem;

src/components/TodoList.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import React from 'react';
33
// COMPONENT
44
import TodoItem from './TodoItem';
55

6-
const TodoList = ({ todoItems }) => (
6+
const TodoList = ({ todoItems, onRemoveTodo }) => (
77
<ul>
88
{
99
todoItems && // Check if todoItems exists
@@ -12,7 +12,9 @@ const TodoList = ({ todoItems }) => (
1212
todoItems.map(({ id, todo }) => ( // If all conditions are met, we render a list of todo items
1313
<TodoItem
1414
key={id}
15+
id={id}
1516
todo={todo}
17+
onRemoveTodo={onRemoveTodo}
1618
/>
1719
))
1820
}

0 commit comments

Comments
 (0)