mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-21 21:25:11 +00:00
fix(nuxt): access shared asyncData state with useNuxtData
(#22277)
This commit is contained in:
parent
6439244c96
commit
a6d6fde9df
@ -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
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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', () => {
|
||||
|
Loading…
Reference in New Issue
Block a user