Home > Enterprise >  Re-render table after deleting item
Re-render table after deleting item

Time:07-23

I'm trying to create a table that shows data from server. The deleting method works but it shows on the table only after refreshing the page. How can I force the component to re-render after deleting an item? this.$forceUpdate doesn't work.

This is the delete function:

async deleteProduct(id) {
    const resp = await fetch(`http://localhost:3005/products/${id}`, {
      method: "DELETE",
    });
}

and that's the table:

<table border="1">
  <tr>
    <th>Product</th>
    <th>Title</th>
    <th>Price</th>
    <th>Options</th>
  </tr>
  <tr v-for="product in products" :title="product.description">
    <td><img :src="product.image" :alt="product.title"/></td>
    <td>{{ product.title }}</td>
    <td>{{ `${product.price}$` }}</td>
    <td>
      <button @click="toggleEdit(product._id)">edit</button> &nbsp
      <button @click="deleteProduct(product._id)">delete</button>
    </td>
  </tr>
</table>

CodePudding user response:

Vue updates based on local data– it tracks the data you have in your component, and when it notices that it has changed, it updates the rendered component to display the changes.

So, when you make a call to your server to delete a product, but don't touch the products array in your local component, Vue has no way to know that anything has changed.

To make Vue aware of the change you need to either:

  1. Refresh the products list with a new copy from server
  2. Manually remove the relevant product locally after deleting it from server (probably what I'd pick)

Either way you'll be letting Vue know about the change in the products list, which is the important part.

CodePudding user response:

May be you should update data like this

async deleteProduct(id) {
  const resp = await fetch(`http://localhost:3005/products/${id}`, {
    method: "DELETE",
  });
  await getProducts() 
}

async getProducts() {
  const res = await apiCall.....
  this.products = res.data;
}
  • Related