'How to Delete a row in a table using ReactJS, while capturing the ID of the deleted object and send it to server

My knowlegde of ReactJS is limited and i wonder how one would delete a selected row and then save the id in a variable to send it to the server, preferably using Axios.

Also is there anyway to not send the Id in the URL?

function Table() {

useEffect(() => {
    Axios.get("http://localhost:3001/api/get/carmodels").then((response) => {
      setCarModelList(response.data)
    })
  }, [])

  const [carModelList, setCarModelList] = useState([])

  const DeleteCar = (val) => { //assigning val the id of the object
    
   const deleteCarModel = Axios.delete(`http://localhost:3001/api/delete/${val}`); //sending it to backend

    return deleteCarModel

  }

  

  const renderTableData = () => {
    return carModelList.map((val) => (
        <tr class>
           <td>{val.id}</td>
            <td>{val.brand}</td>
            <td>{val.model}</td>
            <td>{val.price}</td>
            <td>
                <button>Delete</button> //how do I insert DeleteCar() here?
            </td>
        </tr>))
  }

return (
    <table id="table">
    <thead>
        <tr>
          <th>Id</th>
          <th>Brand</th>
          <th>Model</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
          {renderTableData()}
      </tbody>
      </table>
    );
  

}

export default Table

Much appreciated!



Solution 1:[1]

improving your DeleteCar function with a state update so you can see the changes without reloading your view

const DeleteCar = (val) => {
 // create a new array object
 const next = [...carModelList];
 // remove and save the item of interest to your variable
 const removedItems = next.splice(next.indexOf(val), 1);
 // your axios function formatted for /delete/:id
 const deleteCarModel = Axios.delete(`http://localhost:3001/api/delete/${val.id}`);
 // update react state with the new array
 setCarModelList(next);
}

and to answer the question in your comment:

<button onPress={() => DeleteCar(val)}>Delete</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nestoro