'VueJS - SSR - Wait for async data in created() hook before render
I have a VueJS microfrontend that is SSR thanks to a Ara Framework cluster. In order to make it fully autonomous I would like it to fetch data in the created() hook before the render occurs so that I have a fully complete DOM rendered in SSR.
Logging showed the problem is created() does not wait for my axios data call to end wheter I use async/await, then() or a classic Promise. Then it either fails on DOM or renders a empty dom if I add a v-if="data"
The idea would be to have a functionnal asyncData() like in Nuxt without to have using the whole framework as I have Ara Framework already applying SSR to my Vue app.
created() {
return new Promise(resolve => {
console.log('created')
const { interfaceIn, InterfaceEnum } = this.interfaceService
console.log('1')
if (this.hydratation) {
this.article = interfaceIn(InterfaceEnum.ARTICLE, this.hydratation)
} else {
console.log('1,5')
this.utils.api
.mainGet(
axios,
this.$utils.api.getHostByContext('ctx1', 'ctx2'),
`/news/${this.slug}`,
'Article'
)
.then(data => {
console.log('2')
this.article = interfaceIn(InterfaceEnum.ARTICLE, data.article)
console.log('3')
resolve()
})
console.log('4')
// this.article = interfaceIn(InterfaceEnum.ARTICLE, article)
console.log(this.article.id)
}
})
// this.loading = false
// this.loading = true
}
console output on SSR http call
HTTP call used with ara Framework
Minimal repro is quite complex to provide as it requires the microfrontend + working ara framework cluster for SSR
Thanks
Solution 1:[1]
Answer was to use the serverPrefetch() lifeCycle hook designed for this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thibault Marhem |