I want to delete this TODO with or without using a unique key
this is the HOOK code
const [todos, setTodos] = useState([{}])
const [user, setUser] = useState({
id: uuidv4(),
name: '',
email: '',
phone: '',
})
This one is the Function to set Input and delete a todo
const addTodo = (e) => {
e.preventDefault()
setTodos([...todos, user])
console.log(addTodo)
}
console.log(user)
const delTodo = (e, id) => {
e.preventDefault()
console.log(id)
todos.splice(id, 1)
setTodos([...todos])
}
Here These are being mapped
{todos.map((todo) => (
<div>
<li key={todo.id}>
{todo.name}, {todo.email}, {todo.phone}
</li>
<button onClick={delTodo} color='danger'>
Delete
</button>
</div>
))}
This is what i get when i console.log
CodePudding user response:
Update your delTodo function as below.
splice uses first parameter as start index from array that you want to remove and second parameter is deleteCount. So in your case you need to get index of your object.
You can get index of object with indexOf(). It will return -1 of object does not belong to that array. So add if (index != -1) { } and then you can use todos.splice(index, 1); inside it.
const delTodo = (e, id) => {
e.preventDefault();
console.log(id);
let index = todos.indexOf(id);
if (index != -1) {
todos.splice(index, 1);
}
setTodos([...todos]);
}
