Which VueJS lifecycle hook must Asynchronous HTTP requests be called in?

Baalateja Kataru picture Baalateja Kataru · Mar 30, 2018 · Viewed 16.8k times · Source

I'd like to know how before I render a page, I want to send an async GET request to my server to retrieve data and populate the properties in data. I heard the best way to do this is to call the function that sends this request in one of the three lifecycle hooks Vue js offers that operate before the DOM is rendered. The three are beforeCreate(), created(), beforeMount(). Which one must this request be called in ideally? And why?

Answer

acdcjunior picture acdcjunior · Mar 30, 2018

TL;DR in the general (and safe) case, use created().

Vue's initialization code is executed synchronously.

Technically, any ASYNChronous code you run in beforeCreate(), created(), beforeMount() will only respond after all of those hooks finish. See demo:

new Vue({
  el: '#app',
  beforeCreate() {
    setTimeout(() => { console.log('fastest asynchronous code ever') }, 0);
    console.log('beforeCreate hook done');
  },
  created() {
    console.log('created hook done');
  },
  beforeMount() {
    console.log('beforeMount hook done');
  },
  mounted() {
    console.log('mounted hook done');
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
  Check the console.
</div>

In other words, if you make an Ajax call in beforeCreate(), no matter how fast the API responds, the response will only be processed way later, way after the created() has been executed.


What should guide your decision, then?