Where is the ideal place to wait for a promise result in the Vue component lifecycle? Here's a runnable example: https://codesandbox.io/s/focused-surf-migyw. I generate a Promise in the created()
hook and await the result in the async mounted()
hook. Is this the correct and most efficient way to utilize the Vue component lifecycle?
Note: I choose not to store the result as a mutation in the store since I may need to call this method multiple times. Instead, I return the Promise which retrieves user details from a REST endpoint.
store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
actions: {
FETCH_PROFILE: async context => {
const profile = { name: "Leos" };
return new Promise(function(resolve, reject) {
window.setTimeout(function() {
resolve(profile);
}, 2000);
});
}
}
});
component.vue
<template>
<div class="hello">
<p>Name = {{this.userProfile.name}}</p>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data: () => ({
userProfile: null,
profilePromise: null
}),
created() {
this.profilePromise = this.$store.dispatch("FETCH_PROFILE");
console.log(`my profile: ${this.userProfile}`);
},
async mounted() {
const response = await this.profilePromise;
console.log(response);
this.userProfile = response;
}
};
</script>