user14407372
user14407372

Reputation:

React - how to delete an item from table

I want to delete an item from my cars table so I get the id of car but when I pass it onClick thats loop and returns id as undefined I don't know why doesn't work even the logic is correct.

Can someone help me to fix this issue please.

here is my code :

CarComponent.jsx :

 constructor(props) {
      super(props);
      this.deleteC = this.deleteC.bind(this);
      this.state = {
        idCars: null,
        carName: "",
        carModel: "", 
        cars: [],
        submitted: false
      };

       deleteC(idCars) {   
          DataService.delete(this.idCars)
            .then(response => {
              
              this.props.history.push('/Classement');
            
            })
            .catch(e => {
              console.log(e);
            });
        }
render() {
      const { cars } = this.state;
              return (
            <div >
<tbody>
                    {cars &&
                      cars.map(data => (
                        <tr >
                        
                        <th scope="row">{data.idCars}</th>  
                      
                      <td>{data.carName}</td>
                      <td>{data.carModel}</td>
                      <td>
                      <Link to={"/update/" + data.idCars}
                        className="btn btn-info"
                        >
                        Edit
                       </Link>
                    {data.idCars}
                      <button  className="btn btn-danger"  onClick={this.deleteC(data.idCars)}>
                        Remove
                      </button>
                        </td> 

And the result I get in the console is :

enter image description here

The error loop & dont stop

Upvotes: 0

Views: 149

Answers (1)

Shyam
Shyam

Reputation: 5497

You need to make few changes in your code ,

  1. Your onClick handler needs to be an inline function,
  <button  className="btn btn-danger"  onClick={() => this.deleteC(data.idCars)}>
     Remove
  </button>
  1. You need to use the argument idCars , remove the this
deleteC(idCars) {
  DataService.delete(idCars)
    .then((response) => {
      this.props.history.push("/Classement");
    })
    .catch((e) => {
      console.log(e);
    });
}

Upvotes: 1

Related Questions