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
CodePudding user response:
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)
CodePudding user response:
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);
};
CodePudding user response:
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);
};