Issue with Vue JS reactivity not being updated when using this.$set

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">&nbsp;</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">&nbsp;</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.

https://i.sstatic.net/zB5X8.png

Answer №1

An issue may arise due to the absence of a key in your v-for

<tr v-for="(service, index) in services">

You can utilize the key based on the index, but this approach might lead to problems at times (such as when deleting an item from an array, causing the last DOM object to be removed due to shifting keys)

<tr v-for="(service, index) in services" :key="index">

It is recommended to use something unique from the data like

<tr v-for="(service, index) in services" :key="service.id">>

Answer №2

Big shoutout to @Daniel for pointing out the solution! It turns out my ajax call was returning the field as a string instead of the number value I was expecting (since it's set as an integer in MySQL).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for navigator.credentials.create returning Credential instead of PublicKeyCredential in TypeScript?

I am currently using typescript version 5.6 ("typescript": "~5.6") While trying to implement WebAuth, I noticed that the navigator.credentials.create method returns a Promise<Credential | null> https://i.sstatic.net/TMjU65xJ.png https://i.sstatic.n ...

Issue with Datepicker validation not functioning correctly following a BootStrap update

After submitting the form, the date-picker field correctly validates and highlights it as mandatory. However, even after selecting a date from the picker, the validation error does not disappear. The field continues to be highlighted in red, preventing the ...

Tips for resolving Cross-Origin Resource Sharing (CORS) challenges in Dunzo's developer API when making calls from Nuxt.js with AX

Encountering a CORS error when attempting to use the Dunzo developer API. The base URL for the API can be found at This is my code: await axios .get("https://apis-staging.dunzo.in/api/v1/token", { headers: { "client-id&quo ...

Differences between variable scope in Node.js and web browsers when running JavaScript code

When it comes to browser, different JavaScript files share one scope: a.js: var a=1; //by adding "var", we prevent it from becoming a global variable. b.js: console.log(a) //even though a=1, b.js can still access this variable! In Node.js: a.js .... b ...

Tips on sending a form to the server with ajax technology

I'm struggling with sending a button id to my server through ajax in order to submit a form without having to constantly reload the page every time I click on a button. Unfortunately, it's not working as expected and I can't figure out why. ...

Node.js throws an error when accessing req.body as undefined

My task involved creating a basic API using node.js and express, with the addition of body-parser. However, I encountered an issue where req.body was returning undefined. Here is a snippet of my app.js: const express = require('express'); const b ...

Extracting the inner content in the absence of an HTML element, only plain text

My website's platform has some unusual HTML that I need to work with. There is a section of code that looks like this: <div class="report-description-text"> <h5>Description</h5> Welcome to Ushahidi. Please replace this report with a ...

Can you determine if there are any updates that could potentially cause errors for a PHP package?

Currently, I am working on a project using Laravel and VueJs. I am in the process of upgrading Laravel from version 5.8 to 6.0 following the official documentation guidelines. The documentation advises: "Next, examine any third-party packages used ...

Guide on transferring datetime information from a popup dialog to an MVC controller

My goal is to create a button that, when clicked, opens a dialog allowing the selection of start and end dates. Upon clicking ok/submit, the selected datetime should be passed to a controller [HttpPost] action method. Here's what I have attempted so f ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

Issue regarding ports: deployment of a project using vue.js and node.js on Heroku encountered errors

Having issues deploying my fullstack project. It builds and runs smoothly locally, but on Heroku, I encounter a 503 Service Unavailable error after running the 'git push heroku master' command and the subsequent automatic build process. This coul ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet: new Vue ...

Exploring the realm of external variables and scoping within a jQuery function

I am facing an issue with the following code, where I want to execute test() every time the window is resized. var i = 0; var test = (function() { console.log(i++); })(); $(window).resize(function() { test(); }); Code: http://jsfiddle.net/qhoc/N ...

Is there a way to modify the text color within the thumb-label of the Vuetify v-slider component?

Lately, I've been facing some challenges and my objective is to change the color of the thumb label on my v-slider to a custom one that is defined in the component's design. Can anyone provide guidance on how to achieve this? Regards, Joost ...

Why are divs appearing over a three js animation when scrolling down on a desktop but not on a mobile device?

I have a Three js animation in the body of the document: container = document.createElement( 'div' ); document.body.appendChild( container ); There are two overlaying divs set with the following styles: #holder { z-index: 1; position: abso ...

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...