mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-17 03:14:46 +00:00
a5dad0d2e8
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Daniel Roe <daniel@roe.dev>
25 lines
778 B
TypeScript
25 lines
778 B
TypeScript
import { useNuxtApp } from '../nuxt'
|
|
import type { NuxtPayload } from '#app'
|
|
|
|
/**
|
|
* 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
|
|
*/
|
|
export const useHydration = <K extends keyof NuxtPayload, T = NuxtPayload[K]> (key: K, get: () => T, set: (value: T) => void) => {
|
|
const nuxt = useNuxtApp()
|
|
|
|
if (import.meta.server) {
|
|
nuxt.hooks.hook('app:rendered', () => {
|
|
nuxt.payload[key] = get()
|
|
})
|
|
}
|
|
|
|
if (import.meta.client) {
|
|
nuxt.hooks.hook('app:created', () => {
|
|
set(nuxt.payload[key] as T)
|
|
})
|
|
}
|
|
}
|