diff --git a/packages/nuxt/src/app/composables/asyncData.ts b/packages/nuxt/src/app/composables/asyncData.ts index cd50a3c549..62cae6ecd9 100644 --- a/packages/nuxt/src/app/composables/asyncData.ts +++ b/packages/nuxt/src/app/composables/asyncData.ts @@ -146,6 +146,8 @@ export function useAsyncData< // Create or use a shared asyncData entity if (!nuxt._asyncData[key] || !options.immediate) { + nuxt.payload._errors[key] ??= null + nuxt._asyncData[key] = { data: ref(getCachedData() ?? options.default!()), pending: ref(!hasCachedData()), @@ -153,6 +155,7 @@ export function useAsyncData< status: ref('idle') } } + // TODO: Else, somehow check for conflicting keys with different defaults or fetcher const asyncData = { ...nuxt._asyncData[key] } as AsyncData @@ -373,11 +376,11 @@ export function clearNuxtData (keys?: string | string[] | ((key: string) => bool nuxtApp.payload.data[key] = undefined } if (key in nuxtApp.payload._errors) { - nuxtApp.payload._errors[key] = undefined + nuxtApp.payload._errors[key] = null } if (nuxtApp._asyncData[key]) { nuxtApp._asyncData[key]!.data.value = undefined - nuxtApp._asyncData[key]!.error.value = undefined + nuxtApp._asyncData[key]!.error.value = null nuxtApp._asyncData[key]!.pending.value = false nuxtApp._asyncData[key]!.status.value = 'idle' } diff --git a/packages/nuxt/src/app/nuxt.ts b/packages/nuxt/src/app/nuxt.ts index 4d635753f0..1a933c2a21 100644 --- a/packages/nuxt/src/app/nuxt.ts +++ b/packages/nuxt/src/app/nuxt.ts @@ -81,7 +81,7 @@ export interface NuxtPayload { description: string data?: any } | null - _errors: Record + _errors: Record [key: string]: unknown } @@ -104,7 +104,7 @@ interface _NuxtApp { _asyncData: Record pending: Ref - error: Ref + error: Ref status: Ref } | undefined> diff --git a/test/nuxt/composables.test.ts b/test/nuxt/composables.test.ts index eee928d2da..8d8ad83c4d 100644 --- a/test/nuxt/composables.test.ts +++ b/test/nuxt/composables.test.ts @@ -125,6 +125,14 @@ describe('useAsyncData', () => { expect(pending.value).toBe(false) }) + // https://github.com/nuxt/nuxt/issues/23411 + it('should initialize with error set to null when immediate: false', async () => { + const { error, execute } = useAsyncData(() => ({}), { immediate: false }) + expect(error.value).toBe(null) + await execute() + expect(error.value).toBe(null) + }) + it('should be accessible with useNuxtData', async () => { await useAsyncData('key', () => Promise.resolve('test')) const data = useNuxtData('key')