I am creating a list of tasks (simple todo app) using React Hooks and I'm having some issues while deleting one item. I am rendering that list of tasks from an array in the state. I am getting the id of that item, finding the index inside the array, splicing and then setting the new spliced array as the state again, and while I can see the changes on my console, my ui never gets updated. I tried using the useEffect hook but also didn't work out. Can someone please explain what am I doing wrong? Here's my code on the parent component
const [ todoList, setTodoList ] = useState(data);
const handleToggleComplete = (id) => {
let mapped = todoList.map(task => {
return task.id === Number(id) ? { ...task, complete: !task.complete } : { ...task};
});
setTodoList(mapped);
}
const deleteItem = (id) => {
// gets id of the button triggered
const index = todoList.map(todo => todo.id).indexOf(Number(id))
// finds index of that id
const updatedList = [...todoList];
// splices array .splice(index, 1)
updatedList.splice(index, 1)
// sets new array as state
setTodoList(updatedList)
}
return (
<div className="App">
<Header />
<TodoList todoList={todoList} handleToggleComplete={handleToggleComplete} deleteItem={deleteItem}/>
</div>
);
}
and here is my child component
const handleClick = (event) => {
event.preventDefault()
handleToggleComplete(event.currentTarget.id)
}
const handleDelete = (event) => {
event.preventDefault()
deleteItem(event.currentTarget.parentNode.id)
}
return (
<div id={todo.id} onClick={handleClick} className={todo.complete ? "todo strike" : "todo"}>
{todo.task}
<button onClick={handleDelete}>Delete</button>
</div>
);
};