Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
fix(nuxt): use shared state for useAsyncData
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 30, 2022
1 parent d9cf95f commit 5b36d48
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
15 changes: 10 additions & 5 deletions packages/nuxt/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,16 @@ export function useAsyncData<

const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined

const asyncData = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
} as AsyncData<DataT, DataE>
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>

asyncData.refresh = (opts = {}) => {
// Avoid fetching same key more than once at a time
Expand Down
8 changes: 7 additions & 1 deletion packages/nuxt/src/app/nuxt.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-use-before-define */
import { getCurrentInstance, reactive } from 'vue'
import { getCurrentInstance, reactive, Ref } from 'vue'
import type { App, onErrorCaptured, VNode } from 'vue'
import { createHooks, Hookable } from 'hookable'
import type { RuntimeConfig, AppConfigInput } from '@nuxt/schema'
Expand Down Expand Up @@ -66,6 +66,11 @@ interface _NuxtApp {
[key: string]: any

_asyncDataPromises: Record<string, Promise<any> | undefined>
_asyncData: Record<string, {
data: Ref<any>
pending: Ref<boolean>
error: Ref<any>
}>,

ssrContext?: NuxtSSRContext
payload: {
Expand Down Expand Up @@ -113,6 +118,7 @@ export function createNuxtApp (options: CreateOptions) {
}),
isHydrating: process.client,
_asyncDataPromises: {},
_asyncData: {},
...options
} as any as NuxtApp

Expand Down

0 comments on commit 5b36d48

Please sign in to comment.