2021-10-11 17:48:03 +00:00
|
|
|
import type { Ref } from 'vue'
|
|
|
|
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
|
2021-10-12 14:28:49 +00:00
|
|
|
* @param init a function that provides initial value for state if it's not initiated
|
2021-10-11 17:48:03 +00:00
|
|
|
*/
|
2021-10-12 14:28:49 +00:00
|
|
|
export const useState = <T> (key: string, init?: (() => T)): Ref<T> => {
|
2021-10-11 17:48:03 +00:00
|
|
|
const nuxt = useNuxtApp()
|
2021-10-12 14:28:49 +00:00
|
|
|
const state = toRef(nuxt.payload.state, key)
|
|
|
|
if (state.value === undefined && init) {
|
|
|
|
state.value = init()
|
|
|
|
}
|
|
|
|
return state
|
2021-10-11 17:48:03 +00:00
|
|
|
}
|