With my current application, I fetch the contents from the JSON server and display them with having a delete <button> next to them. I want to delete an entry while using window.confirm to confirm to the user if they really want to delete the entry or not. Instead, as soon as the application loads the confirm window pops up and goes through each entry and deletes them all.
Delete handler method:
const handleDelete = person => {
axios
.delete(`${baseURL}/${person.id}`)
.then(response => {
window.confirm(`Delete ${person.name}?`);
setPersons(null)
});
}
Display method:
const filteredNames = persons.filter(person => person.name.toLowerCase().includes(filter.toLowerCase()))
const row_names = () => {
return(
filteredNames.map(person =>
<p key={person.id}>{person.name} {person.number} <button onClick={handleDelete(person)}>delete</button></p>));
}
JSON
{
"persons": [
{
"name": "Arto Hellas",
"number": "(123) 222-9000",
"id": 1
},
{
"name": "Ada Lovelace",
"number": "(281) 555-1000",
"id": 2
},
{
"name": "Dan Abramov",
"number": "(713) 287-6900",
"id": 3
}
]
}
Lastly, when I add an entry using axios.post my console shows index.js:1 Warning: Each child in a list should have a unique "key" prop., I thought axios handles automatic ID'ing. When I add an entry, the JSON file successfully updates with the new entry and their id, is there something else that has to be done?
CodePudding user response:
onClick={handleDelete(person)}
This executes the function immediately, passing it person as an argument. If the function returns a value (it's not, in your case), then this value is assigned to onClick.
You must pass a function without executing it. There are two main ways/syntaxes to do this :
onClick={ handleDelete.bind(this, person) }
which simply binds a function to a context and optional argument(s) without executing it, or as @Martin suggested :
onClick={ () => handleDelete(person) }
This is an anonymous function that, when it will be executed on click, will in turn execute handleDelete(person).
