Nuxt/docs/content/3.docs/1.usage/2.state.md

44 lines
1.1 KiB
Markdown
Raw Normal View History

2021-10-11 17:48:03 +00:00
# State
Nuxt provides `useState` to create a globally shared state.
## `useState`
Within your pages, components and plugins you can use `useState`. It can be used to create your own store implementation.
2021-10-11 21:49:54 +00:00
You can think of it as an SSR-friendly ref in that its value will be hydrated (preserved) after server-side rendering. It is shared across all components.
2021-10-11 17:48:03 +00:00
### Usage
```js
useState<T>(key: string, init?: (()=>T)): Ref<T>
2021-10-11 17:48:03 +00:00
```
* **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
2021-10-11 17:48:03 +00:00
### 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'
export default defineNuxtPlugin((nuxt) => {
const locale = useState(
'locale',
() => nuxt.ssrContext.req.headers['accept-language']?.split(',')[0]
)
2021-10-11 17:48:03 +00:00
})
```
```vue
<script setup>
const locale = useState('locale')
</script>
<template>
Current locale: {{ locale }}
</template>
```