'Why I cant delete todo item in todo list?
What should I do to remove item from my todo list? What did i do wrong?
Here is my code
function App1() {
const myInputValue = useRef();
const [todo, setToDo] = useState([]);
const addItem = (event) => {
event.preventDefault();
const id = uuid();
setToDo([
...todo,
{
id: id,
name: myInputValue.current.value,
},
]);
myInputValue.current.value = "";
};
const removeItem = e => {
const data = todo.filter(el => el.e !== e);
setToDo(data);
};
const listItems = todo.map((element) => (
<li key={element.id}>
{element.name}
<button>Done</button>
<button onClick={() => removeItem(element.id)}>Delete</button>
</li>
));
return (
<div>
<input ref={myInputValue}></input>
<button onClick={addItem}>Add</button>
<ul>
{listItems}
</ul>
</div>
);
}
export default App1;
What should I change in my removeItem function? Where I do a mistake? Please help
Solution 1:[1]
Iam not sure about it, but when you are adding an item, you add an object with these following keys (id and name), so why when you call removeItem, you test with elemnt.e; didn't you mean to write this ? :
todo.filter(el => el.id !== e)
instead of this:
todo.filter(el => el.e !== e)
Solution 2:[2]
Try this
const removeItem = e => { //e is your id so you compare with other obj ids
const data = todo.filter(el => el.id !== e);
setToDo(data);
};
Solution 3:[3]
You are passing the element's name instead of the element itself.
<button onClick={() => removeItem(element.name)}>Delete</button>
Maybe it was better if you to compare the todo's id in your filter function. Try change your removeItem function to be like this.
const removeItem = e => {
const data = todo.filter(el => el.id !== e.id);
setToDo(data);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The Dnino |
| Solution 2 | Shivansh Verma |
| Solution 3 | Arlle Brasil |
