I am working on a v-for rendered table that displays products. In this table, there is a column for the "active" status where I want users to be able to toggle between active and inactive by clicking a button.
To achieve this functionality, I have implemented a POST call to an API route which updates the status successfully.
The issue I am facing is that VueJS does not update the affected object in the array more than once. The use of this.$set only works for one click. Subsequent clicks do not produce the desired outcome.
Below is the code for my table:
<table class="table table-striped fancy-table">
<thead>
<tr>
<th class="text-center"> </th>
<th>Product/Service</th>
<th class="text-center">Status</th>
<th class="text-center">Date Added</th>
<th class="text-center">QTY Sold</th>
<th class="text-center"> </th>
</tr>
</thead>
<tbody>
<tr v-for="(service, index) in services">
<td class="text-center">
<img v-if="service.featured_image" :src="service.featured_image" class="table-thumb">
<img v-else src="/img/default-product.png" class="table-thumb">
</td>
<td>{{service.service_name}}<span class="secondary">${{parseFloat(service.price).toFixed(2)}}</span></td>
<td class="text-center">
<a href="#" v-if="service.active === 1" @click.prevent="updateStatus(service, index, 0)"><i class="fas fa-circle active"></i></a>
<a href="#" v-else="service.active === 0" @click.prevent="updateStatus(service, index, 1)"><i class="fas fa-circle inactive"></i></a>
</td>
<td class="text-center">{{ service.created_at | moment("dddd, MMMM Do YYYY") }}</td>
<td class="text-center">10</td>
<td class="text-center"><a href="#"><i class="fal fa-edit table-action-btn"></i></a></td>
</tr>
</tbody>
</table>
This is the method I am using to handle the status update:
updateStatus: function(service, index, status) {
// Retrieve the authorized user
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
// Add a role and refresh the list
this.$http.post('/api/vendor/services/update/' + service.id + '?updateActive=' + status, { }, { headers: { Authorization: 'Bearer ' + authUser.access_token } }).then((response) => {
// update this service
this.$set(this.services, index, response.body);
}).catch(function(error){
console.log(error);
})
}
UPDATE:
I have added a :key parameter to the v-for loop in the table but the issue persists. Upon clicking the button, the first request goes as expected. However, subsequent clicks result in continuous posts with updateActive=1 without updating the data in the services array.
Please refer to the screenshot from my network panel after multiple clicks on the button.