I am making an async call to some local json data before my component is created. So this code actually works fine:
beforeCreate : function() {
var self = this;
fetch('/assets/data/radfaces.json')
.then(function(response) { return response.json()
.then( function(data) { self.users = data; } );
})
.catch(function(error) {
console.log(error);
});
},
Now I just want to refactor and move this to a separate method:
beforeCreate : function() {
this.fetchUsers();
},
methods: {
fetchUsers: function() {
var self = this;
fetch('/assets/data/radfaces.json')
.then(function(response) { return response.json()
.then( function(data) { self.users = data; } );
})
.catch(function(error) {
console.log(error);
});
}
}
And now everything stops working. I get an error: app.js:13 Uncaught TypeError: this.fetchUsers is not a function(…)
Why can't I access the fetchUsers method in the beforeCreate hook? What is the work around?
It's because methods hasn't been initialized yet. The easiest way around this it to use the created hook instead:
created : function() {
this.fetchUsers();
},
methods: {
fetchUsers: function() {
var self = this;
fetch('/assets/data/radfaces.json')
.then(function(response) { return response.json()
.then( function(data) { self.users = data; } );
})
.catch(function(error) {
console.log(error);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With