0

Currently the console.log(this.detaliiMP) return an empty array. What I want is to wait until the getData() function fetched the data into detaliiMP array and then to log out to the console the array filled with data.

demo

const app = Vue.createApp({
  data() {
    return {
      detaliiMP: []
    }
  },
  methods: {
    getData() {
      fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.detaliiMP = data)
        .catch(err => console.error(err.message))
    },
    showData() {
      this.getData()
      console.log(this.detaliiMP)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="getData">Get Data</button>

  <button @click="showData">Console LogOut</button>

  <p v-for="item in detaliiMP">{{ item.first_name }}</p>
</div>

I was trying with async/await but clearly I did something wrong, because is not working.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
kevsterdev
  • 45
  • 4
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Nov 17 '22 at 14:28

1 Answers1

0

It's async/await matter.

const app = Vue.createApp({
  data() {
    return {
      detaliiMP: []
    }
  },
  methods: {
    async getData() {
      await fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.detaliiMP = data)
        .catch(err => console.error(err.message))
    },
    async showData() {
      await this.getData()
      console.log(this.detaliiMP)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="getData">Get Data</button>

  <button @click="showData">Console LogOut</button>

  <p v-for="item in detaliiMP">{{ item.first_name }}</p>
</div>
Amini
  • 1,620
  • 1
  • 8
  • 26
  • I was using async/await only on one function at a time, not for both in the same time (duuh). I'm trying to get the logic behind and I don't really understand why we need to use async/await for both functions in the same time? Thanks! – kevsterdev Nov 17 '22 at 14:22