When I click a delete button, a prompt will come up. The prompt works well but somehow it is displaying a weird [object Object], [object Object]. I want it to be such that, when the prompt comes up it refers to the name
in the object. For example, when I click the delete button, the prompt will come up on browser like this,
Do you want to delete jabss ?
But now it is showing,
Do you want to delete [object Object],[object Object],[object Object],[object Object] ?
Here is the delete function button logic and where it is used in the code. How can I fix this ?
const handleDelete = (id) => {
const newPerson = persons.filter((person) => person.id !== id)
if (window.confirm(`Do you want to delete ${newPerson} ?`)) {
personService
.delete(id)
setPersons(newPerson)
}
}
It is used below in the Person
component,
<ul>
{persons.filter((person) => {
if (searchTerm === "") {
return person
} else if (person.name.toLowerCase().includes(searchTerm.toLowerCase())) {
return person
}
}).map((person, id) => {
return (
<Person key={person.id} person={person} deleteButton={()=>handleDelete(person.id)} text='Delete' />
);
})
}
</ul>
db.json where the data is stored,
{
"persons": [
{
"name": "Arto Hellas",
"number": "040-123456",
"id": 1
},
{
"name": "Ada Lovelace",
"number": "39-44-5323523",
"id": 2
},
{
"name": "jabss",
"number": "21321312321",
"id": 4
},
{
"name": "kamal",
"number": "231321321321",
"id": 5
},
{
"name": "jabri juhinin",
"number": "321321321321",
"id": 6
}
]
}
5
Answers
Step 1: fix the filter logic
const newPerson = persons.filter((person) => person.id !== id)
should beconst newPerson = persons.filter((person) => person.id === id)
.Step 2: use find and not filter, to get 1 result and not an array of results.
step 3: display the persons name, not the entire person object, in your string.
You need to use
find
method to return just single record instead offilter
method which returnsarray
, then get thename
property.Something like this would work.
you can save the person to delete temporary all at once without doing a separate
.find
or an extra.filter
I think. there’s no need to find deletedPerson again.
You can simply pass Person object as a parameter.
}