2

I am trying to fetch a json from an api and then format it for later use in google-charts. I fetch the json-file using vue-resource and it works normally, the problem happens when I try to format the received data (update other arrays in data() with the fetched data), the vue component is not updated (the function is in created() ).

When I use a v-on:click the formating is done correctly but when I call the function from created it doesn't work. I tried Vue.set and the splice method, both didn't work.

Goal
Getting the formatData() method to run and update the idArray.

export default {
  name: 'app',
  components: {
    FirstCharts
  },
  data() {
    return {
      apiData: undefined,
      idArray: []
    }
  },
  created() {
    this.loadApi();
  },
  methods: {
    loadApi: function () {
      this.$http.get('https://api.myjson.com/######').then(this.successCallback, this.errorCallback);

    },
    successCallback: function (response) {
      this.apiData = response.data;
    },
    errorCallback: function (response) {
      this.apiData = response.data;
      this.formatData();
      this.$forceUpdate();
    },
    formatData: function () {
      for (var i = 0; i < this.apiData.resourcePlan.length; i++) {
        this.idArray.splice(i, 1, parseInt(this.apiData.resourcePlan[i].resourceID));
        Vue.set(this.idArray, i, parseInt(this.apiData.resourcePlan[i].resourceID));
      }
    }
Phil
  • 157,677
  • 23
  • 242
  • 245
smazigh
  • 21
  • 2
  • Aside from not calling `formatData()` in you're `successCallback`, you're going to run into `this` scope problems with the way you're passing your methods to `then()`. – Phil Aug 12 '19 at 23:55
  • See [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Phil Aug 13 '19 at 00:05

1 Answers1

1

it looks like you are calling formatData in the error callback, not the success callback. see if moving it into success works.

James South
  • 534
  • 4
  • 15