Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 15 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions packages/nuxt/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
}
})
}
}

Expand Down
20 changes: 20 additions & 0 deletions test/nuxt/composables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down