Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wait for fetch function to complete before firing another

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading