-2

I am trying to make a GET request to an API, assign the response to a variable and console.log it. Currently I get null in the console and I don't know why. when I just console.log the res.data I get the data, but for some reason the value does not get assigned to the variable allBeers, how can I save the response to that variable and use it?

Here is my code:

<script>
import axios from "axios";

export default {
  name: "BeerList",
  data() {
    return {
      allBeers: null
    };
  },
  created() {
    axios.get("https://api.punkapi.com/v2/beers").then(res => {
      this.allBeers = res.data;
    });

    console.log(this.allBeers);
  }
};
</script>
  • 1
    your console.log happens before your axios request finishes. You'd need to add the console.logn inside of the `.then` after your assignment – Derek Pollard Oct 21 '20 at 19:29
  • 2
    Does this answer your question? [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) – Derek Pollard Oct 21 '20 at 19:32

2 Answers2

0

Try this solution. axios.get is a promise, and console.log will happen before axios.get is completed. That's why you get null.

<script>
import axios from "axios";

export default {
  name: "BeerList",
  data() {
    return {
      allBeers: null
    };
  },
  created() {
    axios.get("https://api.punkapi.com/v2/beers").then(res => {
      this.allBeers = res.data;
      console.log(this.allBeers);
    });  
  }
};
</script>
Prime
  • 2,809
  • 1
  • 7
  • 23
0

You are saving the response to 'allBeers' variable correctly. The "how to use it" part depends on what you want to do with the data. Vue's 'data' is reactive, so if you want to print it to console when it changes you should use Vue's watcher in your component:

watch: {
    allBeers: function(value) {
        console.log("my new beers:");
        console.log(value);
    }
}

As Vue is UI framework you might want to update your html with the new data, in which case you need to add html template to your component - it will be automatically re-rendered when 'allBeers' change:

template: `<span> {{ allBeers }} </span>`
jviita
  • 114
  • 2
  • 11