0

I have a call in my created method which has an await. I want to know that the results of that call are loaded so that i can conditionally show/hide things in the DOM. Right now it looks like the DOM is being rendered before that method has completed. But I though that methods in created were called before the DOM rendered?

Andrew Vasylchuk
  • 4,671
  • 2
  • 12
  • 30
VBAHole
  • 1,508
  • 2
  • 24
  • 38
  • 1
    Could you pleas provide some code or working fiddle ? – Narendra Jadhav Aug 22 '19 at 16:16
  • 1
    in this question https://stackoverflow.com/questions/45813347/difference-between-the-created-and-mounted-events-in-vue-js there is a comment related to the created step NOT waiting for async api calls to finish – VBAHole Aug 22 '19 at 16:27
  • Putting `await` inside a lifecycle hook will not stop Vue proceeding. More explanation: https://stackoverflow.com/questions/56917250/how-to-stop-vue-life-cycle-from-moving-on-before-vuex-actions-have-completed/56917632#56917632 – skirtle Aug 22 '19 at 16:52

1 Answers1

2

You're correct in assuming that the created hook runs before the component mounts. However, the lifecycle hooks are not waiting for async calls to complete. If you want to wait for that call to be completed and data to load, you can do so by using a Boolean that you set to true when your data has loaded.

Your template:

<div v-if='dataLoaded'>Now you can see me.</div>

in your vue instace

export default {
  data () {
    return {
      dataLoaded: false
    }
  },
  created () {
    loadMyData().then(data => {
      // do awesome things with data
      this.dataLoaded = true
    })
  }
}

This way you can keep your content hidden until that call has resolved. Take care with the context when you handle the ajax response. You will want to keep this as a reference to the original vue instance, so that you can set your data correctly. Arrow functions work well for that.

Tobias G.
  • 341
  • 1
  • 8