fix(nuxt): access shared asyncData state with useNuxtData (#22277)

This commit is contained in:
Maik Kowol 2024-03-15 17:40:00 +01:00 committed by GitHub
parent 6439244c96
commit a6d6fde9df
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 33 additions and 2 deletions

View File

@ -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<DataT = any> (key: string): { data: Ref<DataT | null
}
return {
data: toRef(nuxtApp.payload.data, key)
data: computed({
get () {
return nuxtApp._asyncData[key]?.data.value ?? nuxtApp.payload.data[key]
},
set (value) {
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = value
} else {
nuxtApp.payload.data[key] = value
}
}
})
}
}

View File

@ -274,6 +274,26 @@ describe('useAsyncData', () => {
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', () => {