Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  60] [ 1]  / answers: 1 / hits: 20535  / 7 Years ago, thu, december 14, 2017, 12:00:00

I'm trying to call GetLikes(item.id) method which is in a forEach and within my axios.get function. I get back an error stating TypeError: Cannot read property 'GetLikes' of undefined.



If I comment the method I can see that I'm able to get all items and their ids however when I uncomment the method it no longer works.



axios
.get(/api/endpoint)
.then(response => {
this.data = response.data;
this.data.forEach(function(item) {
console.log(found: , item)
console.log(found id: , item.id)
this.GetLikes(item.id);
});
})


Output with code above:
It seems that it cannot get id 1 for some reason although the same code gets id 1 just without the method below



found:  {…}
found id: 2
TypeError: Cannot read property 'GetLikes' of undefined


Output with this.GetLikes(item.id) being commented out:



found:  {…}
found id: 2
found: {…}
found id: 1


^Above clearly can get all the items so why do I get an undefined if I try to call a method on those items?



The below code works (it gets the correct likes). I use this when a user presses like however I also need to initially get all the likes which is what I'm trying to do above.



Like(id) {
axios
.post(/like/ + id)
.then(response => {
this.GetLikes(id);
})
}


What am I missing here?


More From » vue.js

 Answers
19
this.data.forEach(function(item) {
console.log(found: , item)
console.log(found id: , item.id)
this.GetLikes(item.id);
});


The above code creates a new scope for this so you get property 'GetLikes' of undefined for the function scope of forEach



You don't get this problem with



  axios
.post(/like/ + id)
.then(response => {
this.GetLikes(id);
})


because ES6 arrow functions do not bind their own this



You can try doing



axios
.get(/api/endpoint)
.then(response => {
this.data = response.data;
this.data.forEach((item) => {
console.log(found: , item)
console.log(found id: , item.id)
this.GetLikes(item.id);
});
})


which won't bind this in the forEach loop (notice the arrow function)


[#55683] Monday, December 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalyngriseldas

Total Points: 167
Total Questions: 92
Total Answers: 85

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;