1

I'm trying to get a video title from a axios GET to a video API:

// METHOD GETTING A VIDEO ID:

latestVideo(videoID) {

  var self = this;
  var title;

  axios.get('http://video-api.dev/'+videoID)
  .then(response => {
    this.title = response.data.title
    console.log(response.data.title) //returns the correct title
  })
  return title // returns nothing

}

Console log shows the title, but I need to pass this to outside the call function, to have it available in my Vue app.

I've tried declaring var self=this but it does not seem to have any effect. Have I missed something?

Filip Blaauw
  • 731
  • 2
  • 16
  • 29
  • `this.title` != `title` you initialized an empty `var title` and return it empty – Sovalina Jun 05 '18 at 11:55
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Belmin Bedak Jun 05 '18 at 12:12

2 Answers2

0

Well, returns nothing because you are not assigning any value to the variable, you will have to assign the response data to a variable when the request fulfill:

latestVideo(videoID) {

  // var self = this;
  // var title;

  axios.get('http://video-api.dev/'+videoID)
  .then(response => {
    this.title = response.data.title
    console.log(response.data.title) //returns the correct title
  })
  // return title // not needed

}

Then, when the promise (the request) is resolved you can access to the variable from the component (this.title)

You don't have to use the self switch if you are using arrow syntax.

Ander
  • 758
  • 7
  • 15
0

You're returning title, when assigning the response to this.title, try returning this.title. I am making an assumption that latestVideo lives inside a class

class x {

latestVideo(videoID) {
    axios.get('http://video-api.dev/'+videoID)
    .then(response => {
        this.title = response.data.title
        console.log(response.data.title) //returns the correct title
    });

    return this.title
}}
CJBLOC
  • 84
  • 2