mirror of
https://github.com/nuxt/nuxt.git
synced 2025-01-18 17:35:57 +00:00
docs: init function for useState
(#780)
This commit is contained in:
parent
e721fd4236
commit
4b04cdfdf1
@ -12,10 +12,11 @@ You can think of it as an SSR-friendly ref in that its value will be hydrated (p
|
|||||||
### Usage
|
### Usage
|
||||||
|
|
||||||
```js
|
```js
|
||||||
useState(key: string)
|
useState<T>(key: string, init?: (()=>T)): Ref<T>
|
||||||
```
|
```
|
||||||
|
|
||||||
* **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
|
### Example
|
||||||
|
|
||||||
@ -25,8 +26,10 @@ In this example, we use a server-only plugin to find about request locale.
|
|||||||
import { defineNuxtPlugin, useState } from '#app'
|
import { defineNuxtPlugin, useState } from '#app'
|
||||||
|
|
||||||
export default defineNuxtPlugin((nuxt) => {
|
export default defineNuxtPlugin((nuxt) => {
|
||||||
const locale = useState('locale')
|
const locale = useState(
|
||||||
locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0]
|
'locale',
|
||||||
|
() => nuxt.ssrContext.req.headers['accept-language']?.split(',')[0]
|
||||||
|
)
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -4,8 +4,8 @@ import { useNuxtApp } from '#app'
|
|||||||
/**
|
/**
|
||||||
* Create a global reactive ref that will be hydrated but not shared across ssr requests
|
* 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 key a unique key ensuring that data fetching can be properly de-duplicated across requests
|
||||||
* @param init a function that provides initial value for state if it's not initiated
|
* @param init a function that provides initial value for the state when it's not initiated
|
||||||
*/
|
*/
|
||||||
export const useState = <T> (key: string, init?: (() => T)): Ref<T> => {
|
export const useState = <T> (key: string, init?: (() => T)): Ref<T> => {
|
||||||
const nuxt = useNuxtApp()
|
const nuxt = useNuxtApp()
|
||||||
|
Loading…
Reference in New Issue
Block a user