docs: init function for useState (#780)

This commit is contained in:
Anthony Fu 2021-10-12 22:59:19 +08:00 committed by GitHub
parent e721fd4236
commit 4b04cdfdf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 6 deletions

View File

@ -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<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
@ -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]
)
})
```

View File

@ -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 = <T> (key: string, init?: (() => T)): Ref<T> => {
const nuxt = useNuxtApp()