VueJS async component data and promises VueJS async component data and promises vue.js vue.js

VueJS async component data and promises


The solution was the jsfiddle approach, with a twist. This part:

reload: function () {      fetch('/data/api', {        method: 'get'      }).then(function (response) {        return response.json();      }).then(function (response) {        if (response.status == "success") {          this.records = response.payload;        } else {          console.error(response.message);        }      }).catch(function (err) {        console.error(err);      });    }

needed a .bind(this) in the part which sets the this.records value after the fetch, like so:

reload: function () {      fetch('/data/api', {        method: 'get'      }).then(function (response) {        return response.json();      }).then(function (response) {        if (response.status == "success") {          this.records = response.payload;        } else {          console.error(response.message);        }      }.bind(this)).catch(function (err) {        console.error(err);      });    }

This post was what made it click for me.

Lesson learned: in modern JS, always keep scope in mind.