From 1c8b751cfadbbc2dd6a89fc1c59ed755ed5b9bb5 Mon Sep 17 00:00:00 2001 From: pooya parsa Date: Mon, 15 Nov 2021 21:41:05 +0100 Subject: [PATCH] docs: improve `useState` with shared composable (#1945) --- docs/content/3.docs/1.usage/2.state.md | 62 ++++++++++++++------- examples/use-state/app.vue | 4 +- examples/use-state/composables/states.ts | 1 + examples/use-state/plugins/locale.server.ts | 8 +-- 4 files changed, 50 insertions(+), 25 deletions(-) create mode 100644 examples/use-state/composables/states.ts diff --git a/docs/content/3.docs/1.usage/2.state.md b/docs/content/3.docs/1.usage/2.state.md index 378cfe7696..6a21ab774b 100644 --- a/docs/content/3.docs/1.usage/2.state.md +++ b/docs/content/3.docs/1.usage/2.state.md @@ -1,44 +1,68 @@ # State -Nuxt provides `useState` to create a globally shared state. +Nuxt provides `useState` to create a globally shared state within the context. -## `useState` +`useState` is SSR-friendly `ref` replacement in that its value will be hydrated (preserved) after server-side rendering and is shared across all components using a unique key. -Within your pages, components and plugins you can use `useState`. It can be used to create your own store implementation. +::alert{icon=⚠️} +Never define `const state = ref()` outside of ` -### Example + +``` + +## Example In this example, we use a server-only plugin to find about request locale. -```ts [plugins/locale.server.ts] -import { defineNuxtPlugin, useState } from '#app' +```ts [composables/states.ts] +export const useLocale = () => useState('locale', () => 'en') +``` -export default defineNuxtPlugin((nuxt) => { - const locale = useState( - 'locale', - () => nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] - ) +```ts [plugins/locale.server.ts] +export default defineNuxtPlugin((nuxtApp) => { + const locale = useLocale() + locale.value = nuxtApp.ssrContext?.req.headers['accept-language']?.split(',')[0] }) ``` -```vue +```vue [app.vue] diff --git a/examples/use-state/composables/states.ts b/examples/use-state/composables/states.ts new file mode 100644 index 0000000000..b142eba6e9 --- /dev/null +++ b/examples/use-state/composables/states.ts @@ -0,0 +1 @@ +export const useLocale = () => useState('locale') diff --git a/examples/use-state/plugins/locale.server.ts b/examples/use-state/plugins/locale.server.ts index 52ed70d8b6..e206f486cc 100644 --- a/examples/use-state/plugins/locale.server.ts +++ b/examples/use-state/plugins/locale.server.ts @@ -1,6 +1,4 @@ -import { useState } from '#app' - -export default defineNuxtPlugin((nuxt) => { - const locale = useState('locale') - locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] +export default defineNuxtPlugin((nuxtApp) => { + const locale = useLocale() + locale.value = nuxtApp.ssrContext?.req.headers['accept-language']?.split(',')[0] })