AllTheQuestions
AllTheQuestions

Reputation: 23

Callback function in Axios returning error (using Vue, no jQuery)

I am using Axios with the Vue Javascript framework to loop through an array. I'm trying to set each element in the array to the result of the API call for that element. My functions were not running in order, so I tried using a callback function but it returns an error.

I have looked through other answers(which is why I'm trying to use a callback function) but I still can't get my code to work.

I have a CodePen that shows my problem:

https://codepen.io/thwaawaa/pen/VoEbqR

The CodePen console gives me this error:

[object Error] {
  column: 19,
  line: 34,
  sourceURL: “some long link”
}

Upvotes: 1

Views: 572

Answers (1)

Abdelillah Aissani
Abdelillah Aissani

Reputation: 3108

here is a working fork with no errors : Codepen

the issue you had is that the this.word inside your then callback was not defined because you didn't bind the vue this inside it ...also you handled the response by using 2 thens so the first one was handling the response but it wasn't returning anything to the second one that's why response was undefined to fix this just use one then or return a value from one and chain it to the other then after it.... i would recommend removing the first one on your axi method and add the code inside it on the other then also like we said you have to bind then and you can do that by replacing :

then(function(response){
  var r = response.data[0].phonetic;
  this.word[x] = r;
})

with this :

then((response) => {
  var r = response.data[0].phonetic;
  this.word[x] = r;
})

the arrow function will bind the this implicitly so your function now knows what this means and it won't trigger the catch

Upvotes: 2

Related Questions