6

I've made a get request using Axios which returns some data as expected, but I cannot access the app's data properties in the mounted function to assign the results of the request. The console log to this.productList returns undefined. Can anyone point me in the right direction?

new Vue({
    el: '#products',
    data: function(){
        return{
            test: 'Hello',
            productList: null
        }
    },
    mounted: function(){
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response){
            console.log(response.data);
            console.log(this.productList)
        }).catch(function(error){
            console.log(error);
        })
    }
    
})
Phiter
  • 14,570
  • 14
  • 50
  • 84
Chris Wickham
  • 521
  • 2
  • 5
  • 19
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – t.niese Aug 20 '18 at 11:25

1 Answers1

21

Because in that function, this doesn't refer to your vue instance. It has another meaning.

You can make a temporary variable to hold the value of this in the outer function, like this:

mounted: function() {

  let $vm = this;

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response) {
    console.log(response.data);
    console.log($vm.productList)
  }).catch(function(error) {
    console.log(error);
  })
}

Or you can use the nicer arrow functions:

mounted: function() {

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then((response) => {
    console.log(response.data);
    console.log(this.productList)
  }).catch(function(error) {
    console.log(error);
  })
}
Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Thanks for these answers. Why does the use of the arrow functions change what 'this' references? – Chris Wickham Aug 20 '18 at 11:32
  • 1
    Check [this](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) out – Phiter Aug 20 '18 at 11:33
  • Your answer worked in my case as i assigned "this" to a variable but can you explain how it worked – Mohammad Fahad Rao Jun 09 '21 at 08:27
  • 1
    @MohammadFahadRao `this` is a reserved variable that depends on the scope it's accessed on. If you try to access `this` in a inner function, it will have a different value than the one in the outer function. By attributing `this` from the parent scope to a variable, you can access it in inner scopes. – Phiter Jun 10 '21 at 15:14