0

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?

2 Answers2

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)

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
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);
    });
  })
codejockie
  • 9,020
  • 4
  • 40
  • 46