2022-09-14 09:22:03 +00:00
|
|
|
import { useNuxtApp } from '../nuxt'
|
2023-10-30 21:05:02 +00:00
|
|
|
import type { NuxtPayload } from '../nuxt'
|
2021-01-18 12:46:19 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Allows full control of the hydration cycle to set and receive data from the server.
|
|
|
|
* @param key a unique key to identify the data in the Nuxt payload
|
|
|
|
* @param get a function that returns the value to set the initial data
|
|
|
|
* @param set a function that will receive the data on the client-side
|
2024-01-19 17:03:30 +00:00
|
|
|
* @since 3.0.0
|
2021-01-18 12:46:19 +00:00
|
|
|
*/
|
2023-06-22 13:14:21 +00:00
|
|
|
export const useHydration = <K extends keyof NuxtPayload, T = NuxtPayload[K]> (key: K, get: () => T, set: (value: T) => void) => {
|
2021-08-27 13:30:53 +00:00
|
|
|
const nuxt = useNuxtApp()
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2023-08-07 22:03:40 +00:00
|
|
|
if (import.meta.server) {
|
2021-01-18 12:46:19 +00:00
|
|
|
nuxt.hooks.hook('app:rendered', () => {
|
|
|
|
nuxt.payload[key] = get()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-08-07 22:03:40 +00:00
|
|
|
if (import.meta.client) {
|
2021-01-18 12:46:19 +00:00
|
|
|
nuxt.hooks.hook('app:created', () => {
|
2023-06-22 13:14:21 +00:00
|
|
|
set(nuxt.payload[key] as T)
|
2021-01-18 12:46:19 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|