Alexmedkex
Alexmedkex

Reputation: 457

Update v-for list items that depend on a promise, after promise resolves.

I have a list that iterates through an array of objects, and generates list items that depends on the current object.

A calculation has to be made with the object as parameter, which returns a promise. The issue is that when the list is rendered, it only has access to the promise object (which is pending), and doesn't update once it 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>

How can I get the desired behaviour?

Upvotes: 6

Views: 2766

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

Something like this should work for you. Basically, store the asynchronous response in a reactive array when the promise returns. Since it's reactive, the promise response will automatically be displayed once each promise return.

<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() {
    // sample load orders
    sampleLoadOrdersData().then(response => {
      this.orders = response;
      this.loadAsyncData();
    });
  },
  methods: {
    loadAsyncData() {
      // async await version
      this.orders.map(async (order, i) => {
        const response = await asyncFunction(order);
        this.$set(this.asyncDataHolder, i, response);
      });

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

Upvotes: 5

Related Questions