fix(nuxt): await plugin asyncdata promises in nuxt hook (#9616)

This commit is contained in:
Evgeny Yurkin 2022-12-11 00:44:29 +02:00 committed by GitHub
parent ac61b2b69a
commit 4641e8e504
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 9 additions and 3 deletions

View File

@ -187,7 +187,11 @@ export function useAsyncData<
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
if (getCurrentInstance()) {
onServerPrefetch(() => promise)
} else {
nuxt.hook('app:created', () => promise)
}
}
// Client side

View File

@ -381,6 +381,7 @@ describe('plugins', () => {
it('async plugin', async () => {
const html = await $fetch('/plugins')
expect(html).toContain('asyncPlugin: Async plugin works! 123')
expect(html).toContain('useFetch works!')
})
})
@ -885,7 +886,7 @@ describe.skipIf(process.env.NUXT_TEST_DEV || isWindows)('payload rendering', ()
it('renders a payload', async () => {
const payload = await $fetch('/random/a/_payload.js', { responseType: 'text' })
expect(payload).toMatch(
/export default \{data:\{rand_a:\[[^\]]*\]\},prerenderedAt:\d*\}/
/export default \{data:\{hey:{[^}]*},rand_a:\[[^\]]*\]\},prerenderedAt:\d*\}/
)
})

View File

@ -1,11 +1,12 @@
export default defineNuxtPlugin(async (/* nuxtApp */) => {
const config1 = useRuntimeConfig()
await new Promise(resolve => setTimeout(resolve, 100))
const { data } = useFetch('/api/hey', { key: 'hey' })
const config2 = useRuntimeConfig()
return {
provide: {
asyncPlugin: () => config1 && config1 === config2
? 'Async plugin works! ' + config1.testConfig
? 'Async plugin works! ' + config1.testConfig + (data.value?.baz ? 'useFetch works!' : 'useFetch does not work')
: 'Async plugin failed!'
}
}