2

So I have been trying to delete a person from my table with this function:

  const deletePerson = async (id) => {
    await fetch(`http://localhost:3000/people/${id}`, {
      method: "DELETE",
      headers: {
        "Content-type": "application/json"
      }
    })

    await setPeople(people.filter(person => person.id !== id))
  }

and this is the table:

<table>
    <thead>
       <tr>
         <th>#</th>
         <th>Name</th>
         <th>Age</th>
         <th></th>
       </tr>
   </thead>
    <tbody>
       {people.map((person) => (
          <tr key={person.id + 1}>
            <td>{person.id}</td>
            <td>{person.name}</td>
            <td>{person.age}</td>
            <td>
              <button onClick={deletePerson} id="remove-button">REMOVE</button>
            </td>
         </tr>
       ))}
    </tbody>
</table>

This is the json file (I use mock db, JSON server):

{
  "people": [
    {
      "name": "John Doe",
      "age": "69",
      "id": 1
    },
    {
      "name": "Jane Doe",
      "age": "64",
      "id": 2
    }
  ]
}

When I click the remove button, the delete function doesn't recognize the id (I guess) and this error shows up. I've been trying to solve it on my own but I couldn't succeed. I'm new to ajax and http requests so I'm open to suggestions and information.

Arda Ravel
  • 68
  • 2
  • 7

1 Answers1

1

You are passing the whole person object and you are expecting just the ID. Either pass the ID only, or modify your deletePerson to process the person object:

  const deletePerson = async (person) => {
    await fetch(`http://localhost:3000/people/${person.id}`, {
      method: "DELETE",
      headers: {
        "Content-type": "application/json"
      }
    })
    await setPeople(people.filter(_person => _person.id !== person.id))
  }
Dino
  • 7,779
  • 12
  • 46
  • 85