Troubleshooting: Why isn't my Vue v-for list updating when using v

I have a basic application that retrieves data from an API and displays the array on the screen using a v-for loop.

The array is structured like this

items : [{id : 1, quantity: 2}, {id: 2, quantity: 3} ...]

The loop is set up like this

<div v-for="item in items" :key = "item.id">
    <p>{{ item.name}} </p>
    <button @click="updateQuantity(item.id)">Update Quantity</button>
</div>

I am attempting to change the quantity when a button is clicked, I'm using this function but even though the quantity is being updated, the updated value is not reflecting in the displayed quantity.

updateQuantity(id) {
    // send a request to the API backend
    this.$set(items[id], 'quantity', newQuantity)
    console.log(this.items)
}

Even though the quantity is updated, the new value is not displayed on the page with the v-for loop, what could be the issue and how can I solve it?

Answer №1

It seems like your problem has a simpler solution that I overlooked:
Instead of using post.id as the array index, you should iterate through the array using

v-for="(post, idx) in posts"
and trigger the like function using @click="like(idx)".

NOTE: The response below was written before fully understanding the issue, and is irrelevant to the problem at hand. However, the information may still be helpful.

When using v-for with an array of objects, I prefer passing the entire object to the event handler rather than the index. This way, the object is passed by reference, making the code more concise and easier to read.

Although this approach may not be the most performance-efficient for thousands of components, it can be a more streamlined coding solution.

<template>
  <div v-for="post in posts" :key="`${_uid}_${post.id}`">
    <p>{{ post.title }}</p>
    <button @click="onClickLike(post)">Like</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      posts: []
    }
  },
  async mounted () {
    this.posts = await fetch('https://api.web.site/v2/posts')
  },
  methods: {
    onClickLike (post) {
      post.like++
    }
  }
}
</script>

Alternatively, you would need to use .filter to find the post in the array based on post.id before updating it within the @click handler.

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

I am looking to showcase images beside individuals' names or photos on my website in a vertical arrangement, similar to how it is done on Facebook

Looking for suggestions on how to display images uploaded by users on my webpage in a way similar to Facebook, with the user's photo displayed beside each image. Any recommendations or website links would be greatly appreciated. Thanks, Santosh Sahu ...

|Webview|Best Practices for Integrating Upload Script

I am currently developing an Android app using WebView and I need to implement a code for uploading on Android. I came across the following code snippet and I want to convert it into JavaScript instead of Java (if possible). It needs to be linked to the up ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

What is the method for retrieving JSON data within the AngularJS repeat directive?

I am seeking guidance on how to retrieve the main menu and sub menus separately from a JSON file using ng-repeat. Here are the relevant files: menu.json {"data": { "main menu": { "menu1": [ ...

When using node.js with express, the req.on('end') event is triggered, but the req.on('data') event does not fire

When using body parser, you have the option of either: application/x-www-form-urlencoded body parser or json body parser Both options yield the same results. This is how the API is being called: $.ajax({ type:'post', url:'/ ...

What could be causing my function to fail <object>?

Within index.php, I am calling the function twice, which includes chart.html. index.php chart_line($valuesNight); //first call chart_line($valuesEvening); //second call ?> <?php function chart_line($jsonDataSource){ ?> < ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Enhancing React Native experience by dynamically editing array elements

This code block defines the state of my program, including an array: this.state = { arr: [{ arrid: 0, arrEmail: '', arrName: '', arrPhone: '' }], id: 0, email: "", isChecked: true, name: "", phon ...

Accessing class fields from within an annotation in Typescript

Upon using the code snippet below: @Component({ props: { value: String }, mounted() { //Do something with `bar` this.bar = this.bar + " is now mounted"; } }) export default class Foo extends Vue { priv ...

Launching the forEach function within an ng-repeat loop was it can be done by

I need to implement a function within the ng-repeat that will convert the value of Qprogress object in my JSON into a percentage. I already have the function written, but I am struggling with how to trigger it. I attempted to use a forEach loop inside the ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Utilizing AJAX with FullCalendar to seamlessly insert Bootstrap modal inputs into an SQL table

I've been struggling to implement user input from a modal into my phpMyAdmin database. Any assistance would be highly appreciated. 1) Triggering a modal with the select callback: select: function(start, end, allDay) { $('#myModal') ...

Adjust the scope variable upon submission and refresh the display in AngularJS

Currently, I am working on my first web app using angularjs and facing an issue where the page does not update with new values once the user submits text or numbers in an input box. For this project, I am utilizing Java8, MongoDB, angularJS, and twitter b ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

Retrieving historical data from a MySQL database to display in a div element

My main page features a button that opens a popup. Upon closing the popup, a script is triggered to call a PHP file for selecting data from the database. This selected data is then appended to a specific div within the main page: if (win.closed !== false ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

The value of Vue.js props appears as undefined

It appears that I may be misunderstanding how props work, as I am encountering difficulty passing a prop to a component and retrieving its value, since it always shows up as undefined. Route: { path: '/account/:username', name: 'accco ...

The socket.io.js file could not be located while using (nodejs with express [4.13] and socket.io [1.3])

Currently, I am utilizing express 4.13 and socket.io 1.3.2 along with an express generator. Here is the code snippet from my app.js: var app = express(); var server=require('http').createServer(app).listen(app.get('port'),'127.0. ...