Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
         })    
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading