Reputation: 130
I want to loop through an array containing objects and grab a list of author names from these objects.
To do this I want to write a method which I will forEach()
through. But I can't seem to access my computed property containing the array, when I console.log(articles)
or console.log(this.newsFeed)
it returns undefined
or is just blank.
Clearly I'm doing something wrong but I don't understand what...
Here is my code:
new Vue({
el: '#feed',
data: {
newsFeed: "",
},
created: function() {
console.log('running');
this.getData();
this.filterAuthors();
},
computed:
{
articles: function() {
var articles = this.newsFeed.articles;
return articles;
},
},
methods:
{
getData: function() {
var newsFeed = this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey).then(response => {
this.newsFeed = response.body;
}, response => {
console.error(error);
});
},
filterAuthors: function() {
var articles = this.newsFeed.articles;
var authorsArray = [];
console.log(articles);
// commented out while troubleshooting above
// articles.forEach(function(article) {
// // var authors = article.author;
// // authorsArray.push(authors);
// console.log(authors);
// });
// return authorsArray;
}
}
});
Upvotes: 4
Views: 7322
Reputation: 7867
The HTTP call you make using this.$http
is asynchronous. Since it is asynchronous, you need to tell your code to wait till the call is finished.
In the getData
function, you may write:
getData: function() {
return this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey)
.then(response => {
this.newsFeed = response.body;
}, err => {
console.error(err);
});
}
Then write your created
function so that the filterAuthors
method executes after the call is finished:
created: function() {
console.log('running');
this.getData()
.then(() => {
this.filterAuthors();
});
}
Also, the computed variable is named articles
and therefore can be accessed via this.articles
, not this.newsFeed.articles
.
Upvotes: 5