Home > Blockchain >  how to set the selected row id as a variable in React
how to set the selected row id as a variable in React

Time:11-15

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.

CodePudding user response:

function deletePet(pet) {
  // do some with pet
}

function updatePet(pet) {
  // do some with pet
} 

... ... ...

<td><Button variant="contained" onClick={() => updatePet(pet)}>Edit</Button><Button variant="contained" onClick={() => deletePet(pet)}>Delete</Button></td>
            

You can pass the pet object when clicking the edit/delete button to define which one is editing or deleting.

CodePudding user response:

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();
         })    
 }
  • Related