From 5b36d48a389d918bb87a8fd518b52a923c4f0989 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 30 Aug 2022 11:55:22 +0200 Subject: [PATCH] fix(nuxt): use shared state for `useAsyncData` --- packages/nuxt/src/app/composables/asyncData.ts | 15 ++++++++++----- packages/nuxt/src/app/nuxt.ts | 8 +++++++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/packages/nuxt/src/app/composables/asyncData.ts b/packages/nuxt/src/app/composables/asyncData.ts index 7318718becf..a7596859e43 100644 --- a/packages/nuxt/src/app/composables/asyncData.ts +++ b/packages/nuxt/src/app/composables/asyncData.ts @@ -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 + // 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 asyncData.refresh = (opts = {}) => { // Avoid fetching same key more than once at a time diff --git a/packages/nuxt/src/app/nuxt.ts b/packages/nuxt/src/app/nuxt.ts index 812022729dc..cdada80b45a 100644 --- a/packages/nuxt/src/app/nuxt.ts +++ b/packages/nuxt/src/app/nuxt.ts @@ -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' @@ -66,6 +66,11 @@ interface _NuxtApp { [key: string]: any _asyncDataPromises: Record | undefined> + _asyncData: Record + pending: Ref + error: Ref + }>, ssrContext?: NuxtSSRContext payload: { @@ -113,6 +118,7 @@ export function createNuxtApp (options: CreateOptions) { }), isHydrating: process.client, _asyncDataPromises: {}, + _asyncData: {}, ...options } as any as NuxtApp