Search code examples
arraysvue.jspromisevuejs2javascript-objects

Vue.js: Add Promise result to Array


I have the following Vue.js component:

<template>
  <div>
    <pre>{{ $data }}</pre>
  </div>
</template>

<script>
  import { getPrice, getPriceForTimestamp } from '../api/crypto';
  import { cryptostorage } from '../api/utils';

  export default {
    name: 'test',
    data () {
      return {
        cryptoLocalStorage: cryptostorage.fetch()
      }
    },
    methods: {
      getPriceForAmount() {
        for (let i = 0; i < this.cryptoLocalStorage.length; i++) {
          let cryptoName = this.cryptoLocalStorage[i].title;
          let cryptoDate = this.cryptoLocalStorage[i].date;
          let cryptoAmount = this.cryptoLocalStorage[i].amount;

          let historicPrice = getPriceForTimestamp(cryptoName, cryptoDate);
          Promise.all([historicPrice]).then((values) => {
            this.cryptoLocalStorage[i].purchaseDatePrice = values[0];
            this.cryptoLocalStorage.push({ purchaseDatePrice: values});
          }).catch(e => console.error(e));
        }
      }
    },
    created() {
        this.getPriceForAmount();
    }
  }
</script>

This is what $data returns me:

{
  "cryptoLocalStorage": [
    {
      "id": 0,
      "title": "ETH",
      "amount": "0.5",
      "date": "2018-01-16T12:39:00.000Z",
      "purchaseDatePrice": 1050.26
    },
    {
      "id": 1,
      "title": "BTC",
      "amount": "1",
      "date": "2018-01-09T12:42:00.000Z",
      "purchaseDatePrice": 14468.5
    },
    {
      "id": 2,
      "title": "LTC",
      "amount": "0.003",
      "date": "2017-11-14T12:48:00.000Z",
      "purchaseDatePrice": 62.13
    },
    {
      "purchaseDatePrice": [
        14468.5
      ]
    },
    {
      "purchaseDatePrice": [
        1050.26
      ]
    },
    {
      "purchaseDatePrice": [
        62.13
      ]
    }
  ]
}

The problem is that I have now purchaseDatePrice duplicated and only need it in the object where also ID, title and so on is.

this.cryptoLocalStorage.push({ purchaseDatePrice: values});

is causing the problem but if I remove it, this.cryptoLocalStorage[i].purchaseDatePrice = values[0]; does not work anymore.

I also tried to use this.cryptoLocalStorage[i].push({ purchaseDatePrice: values}); with index but it results to the error TypeError: _this2.cryptoLocalStorage[i].push is not a function


Solution

  • try

    Vue.set(this.cryptoLocalStorage[i], 'purchaseDatePrice', values[0]) instead of

    this.cryptoLocalStorage[i].purchaseDatePrice = values[0];
    

    if purchaseDatePrice property isn't present in initial model of single array item, you can't just add new property to this item. I bet that THIS will explain nature of your problem