8👍
✅
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)
0👍
Use arrow functions for the forEach
as it binds this to the containing scope.
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);
});
})
Source:stackexchange.com