From a6d6fde9dff7396c9af4a38e0759f8183c06505c Mon Sep 17 00:00:00 2001 From: Maik Kowol Date: Fri, 15 Mar 2024 17:40:00 +0100 Subject: [PATCH] fix(nuxt): access shared asyncData state with `useNuxtData` (#22277) --- .../nuxt/src/app/composables/asyncData.ts | 15 ++++++++++++-- test/nuxt/composables.test.ts | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/nuxt/src/app/composables/asyncData.ts b/packages/nuxt/src/app/composables/asyncData.ts index b2d5c2d3a3..319be17438 100644 --- a/packages/nuxt/src/app/composables/asyncData.ts +++ b/packages/nuxt/src/app/composables/asyncData.ts @@ -1,4 +1,4 @@ -import { getCurrentInstance, onBeforeMount, onServerPrefetch, onUnmounted, ref, shallowRef, toRef, unref, watch } from 'vue' +import { computed, getCurrentInstance, onBeforeMount, onServerPrefetch, onUnmounted, ref, shallowRef, toRef, unref, watch } from 'vue' import type { Ref, WatchSource } from 'vue' import type { NuxtApp } from '../nuxt' import { useNuxtApp } from '../nuxt' @@ -461,7 +461,18 @@ export function useNuxtData (key: string): { data: Ref { expect(promiseFn).toHaveBeenCalledTimes(2) }) + + it('should be synced with useNuxtData', async () => { + const { data: nuxtData } = useNuxtData('nuxtdata-sync') + const promise = useAsyncData('nuxtdata-sync', () => Promise.resolve('test'), { default: () => 'default' }) + const { data: fetchData } = promise + + expect(fetchData.value).toMatchInlineSnapshot('"default"') + + nuxtData.value = 'before-fetch' + expect(fetchData.value).toMatchInlineSnapshot('"before-fetch"') + + await promise + expect(fetchData.value).toMatchInlineSnapshot('"test"') + expect(nuxtData.value).toMatchInlineSnapshot('"test"') + + nuxtData.value = 'new value' + expect(fetchData.value).toMatchInlineSnapshot('"new value"') + fetchData.value = 'another value' + expect(nuxtData.value).toMatchInlineSnapshot('"another value"') + }) }) describe('useFetch', () => {