[Vuejs]-Wait for fetch function to complete before firing another

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>

Leave a comment