Yeiye
Yeiye

Reputation: 29

How can i delete data from a table?

I'm creating crud with react and laravel but is my first proyect with this frameworks so i'm beginner programming websites, so i'm trying to delete data from a table, i'm using axios to access laravel routes but in my table continues to show the data, i need you help to delete data from a table.

const handleDeleteItems = () => {
    axios.delete(urlDelete, {
        id:cart.id
    })
    .then(response =>{
        console.log(response);
    })
    .catch(e =>{
        console.log(e.response.data);
    });
} 
           <tbody>
               {cart.map((cart, key) =>{
                   return(
                    <tr key={cart.id}>
                        <td>{cart.name}</td>
                        <td>{cart.price}</td>
                        <td>
                            <Button onClick={handleDeleteItems} variant="danger">Delete</Button>
                        </td>
                    </tr>

                   )
               })}

Upvotes: 0

Views: 312

Answers (2)

Eric Cheng
Eric Cheng

Reputation: 517

I can see you sent a delete call to the server. That suppose to delete that record on server side.

from your logic, you have an array/list cart, you use it to map data on the page.

the problem should be, after you sent delete to the server, in the response, you should refresh your array/list, or you should check the result if success, delete that record manually from your local state.

You need to refresh your local array/list to refresh your display records.

Upvotes: 0

Sivakumar A
Sivakumar A

Reputation: 701

You can try this,

  • Add arrow method to onClick props
{cart.map((cart, key) =>{
    return(
         <tr key={cart.id}>
             <td>{cart.name}</td>
             <td>{cart.price}</td>
             <td>
                 <Button onClick={() => handleDeleteItems(key)} variant="danger">Delete</Button>
             </td>
         </tr>
    )})}
// if "cart" is a state variable
const handleDeleteItem = (key) => {
  const temp = [...this.state.cart];
  temp.splice(index,1);
  this.setState({cart: temp});
}

// if "cart" is a normal variable
const handleDeleteItem = (key) => {
  cart.splice(index,1);
}


Upvotes: 1

Related Questions