Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - axios is undefined when trying to store and display vue-axios response data

I cannot seem to able to get vue-axios to fetch, store and display data in browser. I tried this and getting undefined when getData button is clicked.

new Vue({
  el: '#app',
  data: {
    dataReceived: '',
  },
  methods: {
    getData() {
      axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
        .then(function(response) {
          this.dataReceived = this.response;
          console.log(this.dataReceived);
          return this.dataReceived;
        })
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
  <div id="app">
    <button @click="getData" type="button">getData</button>
    <p>dataReceived: {{ dataReceived }}</p>
  </div>
</body>

</html>
like image 438
Moazzem Hossen Avatar asked Jan 28 '23 08:01

Moazzem Hossen


1 Answers

I would add to @boussadjrabrahim's excellent answer that you need to use a fat arrow notation inside your then callback to make sure that the this keyword is bound to your Vue instance. Otherwise your dataReceived will remain blank.

new Vue({
  el: '#app',
  data: {
    dataReceived: '',
  },
  methods: {
    getData() {
      axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
        .then((response) => {
          this.dataReceived = response.data;
          console.log(this.dataReceived);
          return this.dataReceived;
        })
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <button @click="getData" type="button">getData</button>
    <p>dataReceived: {{ dataReceived }}</p>
  </div>
</body>

</html>
like image 95
Husam Ibrahim Avatar answered Jan 31 '23 23:01

Husam Ibrahim