fix(nuxt): refetch both undefined/null values in useAsyncData (#23351)

This commit is contained in:
warflash 2023-10-16 21:20:02 +02:00 committed by GitHub
parent 34adac661d
commit f4d67a9bcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 39 additions and 2 deletions

View File

@ -143,7 +143,9 @@ export function useAsyncData<
const nuxt = useNuxtApp()
const getCachedData = () => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key]
const hasCachedData = () => getCachedData() !== undefined
const hasCachedData = () => ![null, undefined].includes(
nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key]
)
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key] || !options.immediate) {
@ -253,7 +255,7 @@ export function useAsyncData<
}
}
if (fetchOnServer && nuxt.isHydrating && hasCachedData()) {
if (asyncData.error.value || (fetchOnServer && nuxt.isHydrating && hasCachedData())) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
asyncData.status.value = asyncData.error.value ? 'error' : 'success'

View File

@ -1925,6 +1925,12 @@ describe.skipIf(process.env.TEST_CONTEXT !== 'async')('Async context', () => {
})
describe.skipIf(isWindows)('useAsyncData', () => {
it('works after useNuxtData call', async () => {
const page = await createPage('/useAsyncData/nuxt-data')
expect(await page.locator('body').getByText('resolved:true').textContent()).toContain('resolved:true')
await page.close()
})
it('single request resolves', async () => {
await expectNoClientErrors('/useAsyncData/single')
})

View File

@ -0,0 +1,15 @@
<template>
<div
v-if="!pending"
v-text="'resolved:' + data.resolved"
/>
<div
v-else
v-text="'loading'"
/>
</template>
<script setup>
useNuxtData('call')
const { data, pending } = await useAsyncData('call', () => Promise.resolve({ resolved: true }), { server: false })
</script>

View File

@ -143,6 +143,20 @@ describe('useAsyncData', () => {
expect(useNuxtData('key').data.value).toBeUndefined()
})
it('should be usable _after_ a useNuxtData call', async () => {
useNuxtApp().payload.data.call = null
const { data: cachedData } = useNuxtData('call')
expect(cachedData.value).toMatchInlineSnapshot('null')
const { data } = await useAsyncData('call', () => Promise.resolve({ resolved: true }), { server: false })
expect(cachedData.value).toMatchInlineSnapshot(`
{
"resolved": true,
}
`)
expect(data.value).toEqual(cachedData.value)
clearNuxtData('call')
})
it('should be refreshable', async () => {
await useAsyncData('key', () => Promise.resolve('test'))
clearNuxtData('key')