3

Hey I am trying to make a full stack app with vuejs fastifyjs(node framework). The vue app gets data from the api I developed and also display it in the browser console but it does not render it in the app. I even tried to load it on mount function but nothing happens.

Here is the complete code I am using.

const app = new Vue({
  el:'#app',

  data:{
    infos: [{
      name: 'Vue',
      age: 19,
      imageUrl: 's3.aws.amazon.com'
    }, {
      name: 'Vue 2',
      age: 20,
      imageUrl: 's3.aws.amazon.com2'
    }],
    msg: 'Hello Vuejs!'
  },

  methods:{
    getData: function(){
      axios.get('http://localhost:3000/getData')
        .then(function(result){
          this.infos = result.data
          console.log(infos)
        })
        .catch(function(err){
          console.log(err)
        })
    }
  }
})
<div id="app">
  {{msg}}
  <button v-on:click="getData">Get Data</button><br><br>
  <div v-for="info in infos">
    <br>
    <span>Name: {{info.name}}</span><br>
    <span>Age: {{info.age}}</span><br>
    <span>Image: {{info.imageUrl}}</span><br>
  </div>
</div>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="index.js"></script>

Here is the image of what I am getting.

The default values get rendered and also at the right the array gets logged.

The complete code is here https://github.com/siddiquiehtesham/fullstack-vue-nodejs-api

yqlim
  • 6,898
  • 3
  • 19
  • 43

1 Answers1

3

In your axios request, this is not bound to your Vue instance.

Use arrow function instead to keep the right context:

getData: function() {
  axios.get('http://localhost:3000/getData')
  .then(result => {
    this.infos = result.data
    console.log(this.infos)
  })
  .catch(err => {
    console.log(err)
  })
}

or set a self variable before the request:

getData: function() {
  let self = this
  axios.get('http://localhost:3000/getData')
  .then(function(result) {
    self.infos = result.data
    console.log(self.infos)
  })
  .catch(function(err) {
    console.log(err)
  })
}
Sovalina
  • 5,410
  • 4
  • 22
  • 39
  • Hey that worked ! Thank you. I have a doubt that why do I have to use arrow function instead of normal function? And I was using function keyword because when I was writing everything in arrow functions the getData: was not working but when I wrote function it worked. What's the concept which I am missing or I don't know? – Ehtesham Siddiqui Mar 16 '19 at 15:48
  • 1
    If you want to know more about `this` keyword and its using context here's [a good post](https://stackoverflow.com/a/20279485/9541423) explaining why and how. – Sovalina Mar 16 '19 at 15:57