I am trying to delete a task using handleDelete function, but something get my attention and i don’t know why!
Every time i press the addTodos function, the handleDelete is triggered automatically why is that ?
My aim is to get the id once i press a tag inside the map, but as a weird thing to a beginner as myself i don’t know why once i press the Add button the handleDelete function runs ?
My code :
import { useState } from "react";
import "./App.scss";
function App() {
//Value of Input
const [val, setVal] = useState("");
const [todos, setTodos] = useState([]);
const addTodos = (e) => {
e.preventDefault();
setTodos([...todos, val]);
setVal("");
};
const handleDelete = (id) => {
console.log(id);
};
return (
<div className="App">
{/** On change values*/}
<form onSubmit={addTodos}>
<input
onChange={(e) => setVal(e.target.value)}
value={val}
type="text"
/>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo, key) => (
<div key={key}>
<li>{todo}</li>
<a onClick={handleDelete(key)}>X</a>
</div>
))}
</ul>
</div>
);
}
export default App;
I tried to console log inside the id inside handleDelete function but the console is also triggered from the addTodos function as well!
>Solution :
Change this:
onClick={handleDelete(key)}>X</a>
To this:
onClick={()=> handleDelete(key)}>X</a>
In the first case, you are calling the function handleDelete and pass its return value as an event handler.
In the second case, you are passing a function definition as an event handler, which is the proper way of doing this.