From 320c4098a5e0b071ed464b65aed1851e763755f7 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 27 Jul 2021 11:10:30 +0100 Subject: [PATCH] fix: allow setting ssrRef within `onGlobalSetup` (#523) --- src/runtime/composables/ssr-ref.ts | 25 +++++++++---------------- test/fixture/plugins/global.js | 3 ++- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/runtime/composables/ssr-ref.ts b/src/runtime/composables/ssr-ref.ts index d44c86f8..825ee85e 100644 --- a/src/runtime/composables/ssr-ref.ts +++ b/src/runtime/composables/ssr-ref.ts @@ -25,27 +25,20 @@ export function setSSRContext(app: any) { } const useServerData = () => { - let type: 'globalRefs' | 'ssrRefs' = 'globalRefs' - const vm = getCurrentInstance() + const type: 'globalRefs' | 'ssrRefs' = vm ? 'ssrRefs' : 'globalRefs' - if (vm) { - type = 'ssrRefs' - if (process.server) { - const { ssrContext } = (vm[globalNuxt] || vm.$options).context - ;(ssrContext as any).nuxt.ssrRefs = (ssrContext as any).nuxt.ssrRefs || {} - } + let ssrRefs: Record + + if (vm && process.server) { + const ssrContext = (vm![globalNuxt] || vm!.$options).context.ssrContext! + ssrRefs = (ssrContext.nuxt as any).ssrRefs = + (ssrContext.nuxt as any).ssrRefs || {} } const setData = (key: string, val: any) => { - switch (type) { - case 'globalRefs': - globalRefs[key] = sanitise(val) - break - case 'ssrRefs': - ;(vm![globalNuxt].context.ssrContext as any).nuxt.ssrRefs[key] = - sanitise(val) - } + const refs = ssrRefs || globalRefs + refs[key] = sanitise(val) } return { type, setData } diff --git a/test/fixture/plugins/global.js b/test/fixture/plugins/global.js index 44b29d0a..41e83264 100644 --- a/test/fixture/plugins/global.js +++ b/test/fixture/plugins/global.js @@ -16,7 +16,8 @@ export default () => { onGlobalSetup(() => { const { $config } = useContext() - ssrRef('test') + const a = ssrRef('test') + a.value = 'another' const { title } = useMeta() title.value = 'My fixture'