Refresh the list items in a v-for loop once the promise has successfully resolved

I am working on a scenario where I have a list that iterates through an array of objects, generating list items that are dependent on the current object.

As part of this process, a calculation needs to be performed with the object as a parameter, which in turn returns a promise. The problem I am facing is that once the list is rendered, it only has access to the pending promise object and does not update once the promise resolves.

<md-list id="orderList">
        <md-list-item v-for="order in orders" :key="order.id" @click="orderDialog(order)">
            {{ asyncFunction(order) }}
        </md-list-item>
 </md-list>

I am seeking advice on how to achieve the desired behavior in this situation.

Answer №1

If you're looking for a solution, try storing the asynchronous response in a reactive array whenever the promise is fulfilled. The reactive nature of the array will automatically display the promise response each time it returns.

<template>
    <md-list id="orderList">
        <md-list-item v-for="(order,i) in orders" :key="order.id" @click="orderDialog(order)">
            <template v-if="typeof asyncDataHolder[i] !== 'undefined'">
                {{asyncDataHolder[i]}}
            </template>
        </md-list-item>
    </md-list>
</template>

<script>
export default {
  data: {
    orders: [],
    asyncDataHolder: []
  },
  created() {
    // example: load orders
    sampleLoadOrdersData().then(response => {
      this.orders = response;
      this.loadAsyncData();
    });
  },
  methods: {
    loadAsyncData() {
      // async await method
      this.orders.map(async (order, i) => {
        const response = await asyncFunction(order);
        this.$set(this.asyncDataHolder, i, response);
      });

      // normal promise method
      this.orders.map((order, i) => {
        asyncFunction(order).then(response => {
          this.$set(this.asyncDataHolder, i, response);
        });
      });
    }
  }
};
</script>

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

Generating fresh Mongodb Records versus Appending to a Document's Collection

A device that records temperature data every second feeds into a real-time chart using Meteor.js to display the average temperature over the past 5 seconds. Should each temperature reading be saved as a separate MongoDB document, or should new readings be ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

Error encountered: JSHint is flagging issues with setting a background gradient using

I have been experimenting with animating a background gradient using jQuery, and here is the code snippet I am working with: this.$next.css('line-indent', 0).animate({ 'line-indent': 100 }, { "duration": 750, "step": functi ...

Assigning automatic roles based on the Discord.js v12 presence status of users

When someone is playing, I want to add a role using the presenceUpdate event However, every time I attempt this in discord.js v12, I encounter the following error: TypeError: Cannot read property 'activities' of undefined What mistake am I maki ...

show the day of the week for a specific date saved in a MongoDB database

I need to create a report showing the total number of purchases for each day in the past week, formatted like this: { "sunday":30, "monday":20, ... } Each purchase in the database is structured as follows: { _id: 603fcb ...

Implicitly pass "this" by utilizing an inline event listener

var functionVariable = (function() { return { 'initialize': function(className) { // Here, I need to access the <a> tag and apply the specified className } }; }()); <a href="#" onmouseover="functionVariable.i ...

Tips for creating a script that compiles all SCSS files into CSS within a Vue 3 project

Within my project, there exists a file named index.scss located in the src/assets/styles directory. Adjacent to this file are multiple folders housing SCSS files that are ultimately imported into index.scss. My objective is to devise a script within the pa ...

Choosing JavaScript

<select> <script type="text/javascript"> $.get( 'http://www.ufilme.ro/api/load/maron_online/470', function(data){ var mydata = new Array(); var i = 0; // индекс масси ...

The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field. Here is my HTML code: <div class="date ui-input"> <input type="text" name="dateD" [ngModel]="model.date | dat ...

Struggling with transferring a JavaScript array to the current page using AJAX

This might sound like a common question, but I have conducted thorough research and none of the solutions provided have worked for me. I have a javascript array structured as follows: [from: "2016-04-01", to: "2016-04-14"] I am sending this array via AJA ...

Error encountered in React V16.7: The function is not valid and cannot be executed

import React, { useContext } from 'react'; The useContext function is returning undefined. Error Details: Uncaught (in promise) TypeError: Object(...) is not a function Error occurred when processing: const context = useContext(UserCon ...

"Toggling the parent element through jQuery within a search function

I have a similar structure in my table: <input id="mySearch" placeholder="Search..." type="text"/> <table> <th>Main header</th> <tbody id="searchable"> <tr class="parent"><td>Parent</td></tr> ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

How can I implement a thumbnail editing feature similar to Facebook's display image uploader in an Asp.net application using c#?

How can I upload an image and display a specific part of it in a thumbnail of a custom size? I also want to personalize the appearance of the thumbnail. ...

Is there a way to change the domain for all relative URLs on an HTML page to a different one that is not its current domain, including in HTML elements and JavaScript HTTP Requests?

I am dealing with a situation where my page contains "domain relative URLs" like ../file/foo or /file/foo within a href attributes, img src attributes, video, audio, web components, js ajax calls, etc. The issue arises when these URLs need to be relative ...

Restrict the number of rows in a CSS grid

Hello there, I am in the process of creating an image gallery using CSS grid. Specifically, my goal is to initially show just one row of images and then allow users to click a "Show more" button to reveal additional images. You can see my progress here: ...

remove leading spaces in JavaScript after retrieving data from database

Hey there, I need help with trimming the leading spaces using JavaScript when the value is fetched from a database. I am using JSP tags to retrieve the value and load it into an input field. The issue I'm facing is that if there are any spaces at the ...

JS Data error: The attributes provided must include the property indicated by idAttribute - particularly with regards to hasMany relationships

Encountered Error: The main key for my user model is username. The primary key for my routes is the routename. When my API returns JSONs, they are nested inside data:{} following jsonapi.org specifications. However, this structure differs from what js-dat ...

Sorting a collection of objects into separate arrays

When working with React, here is an example of the state configuration I am using: state = { Producers: [], France: [], Spain: [], Germany: [], Portugal: [], Greece: [], Austria: [], isLoading: false }; I ...

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...