Issue
I am currently trying to add a delete and edit button on each row of a table, I currently am able to make the buttons run the functions just fine but the big issue i am having is that I cannot for the life of me figure out how to get the id of that row and make it into a variable for me to plug into the function.`
function deletePet()
{
fetch("http://localhost:3001/api?act=delete&id="+pet.id+"")
.then(res => res.json())
.then(
(result) => {
fetchPets();
})
}
function updatePet()
{
fetch("http://localhost:3001/api?act=update&id=2&animal=" + name + "&description="+desc+"&age="+age+"&price="+price+"")
.then(res => res.json())
.then(
(result) => {
fetchPets();
});
}
return (<div>
<table>
<tbody>
<tr>
<th>Animal</th>
<th>Description</th>
<th>Age</th>
<th>Price</th>
<th>Action</th>
</tr>
{pets.map(pet => (
<tr key={pet.id}>
<td>{pet.animal}</td>
<td>{pet.description}</td>
<td>{pet.age}</td>
<td>{pet.price}</td>
<td><Button variant="contained" onClick={updatePet}>Edit</Button><Button variant="contained" onClick={deletePet}>Delete</Button></td>
</tr>
))}
so basically I want to click on the delete button on x row and I want it to be deleted with the delete pet function as you can see I tried just putting in pet.id (which obviously doesnt work hahahaha). Any help will be appreciated!
I have tried to make the key into a variable and the pet.id into a variable within the table, as well as create a nested function within the button that will just remove the row but that also didnt work.
Solution
Try with onClick={deletePet(pet.id)}
in the delete button and in you function:
function deletePet(id) {
fetch("http://localhost:3001/api?act=delete&id="+id+"")
.then(res => res.json())
.then(
(result) => {
fetchPets();
})
}
Answered By - Franco Gabriel
Answer Checked By - - Candace Johnson (ReactFix Volunteer)