From 4b04cdfdf10fa4aaa82c8ee03c9fcaaac802e041 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Tue, 12 Oct 2021 22:59:19 +0800 Subject: [PATCH] docs: init function for `useState` (#780) --- docs/content/3.docs/1.usage/2.state.md | 11 +++++++---- packages/nuxt3/src/app/composables/state.ts | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/content/3.docs/1.usage/2.state.md b/docs/content/3.docs/1.usage/2.state.md index 206fa26f93..7a72d22144 100644 --- a/docs/content/3.docs/1.usage/2.state.md +++ b/docs/content/3.docs/1.usage/2.state.md @@ -12,10 +12,11 @@ You can think of it as an SSR-friendly ref in that its value will be hydrated (p ### Usage ```js -useState(key: string) +useState(key: string, init?: (()=>T)): Ref ``` -* **key**: a unique key to ensure that data fetching can be properly de-duplicated across requests +* **key**: a unique key ensuring that data fetching can be properly de-duplicated across requests +* **init**: a function that provides initial value for the state when it's not initiated ### Example @@ -25,8 +26,10 @@ In this example, we use a server-only plugin to find about request locale. import { defineNuxtPlugin, useState } from '#app' export default defineNuxtPlugin((nuxt) => { - const locale = useState('locale') - locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] + const locale = useState( + 'locale', + () => nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] + ) }) ``` diff --git a/packages/nuxt3/src/app/composables/state.ts b/packages/nuxt3/src/app/composables/state.ts index 2d5ac6c458..256e884170 100644 --- a/packages/nuxt3/src/app/composables/state.ts +++ b/packages/nuxt3/src/app/composables/state.ts @@ -4,8 +4,8 @@ import { useNuxtApp } from '#app' /** * Create a global reactive ref that will be hydrated but not shared across ssr requests * - * @param key a unique key to identify the data in the Nuxt payload - * @param init a function that provides initial value for state if it's not initiated + * @param key a unique key ensuring that data fetching can be properly de-duplicated across requests + * @param init a function that provides initial value for the state when it's not initiated */ export const useState = (key: string, init?: (() => T)): Ref => { const nuxt = useNuxtApp()