#coordinate random values between ssr and csr
8 messages · Page 1 of 1 (latest)
im toying around with useHydration but i dont think this is exactly what im looking for
mm i looked at the source code for useHydration and came up with this:
export function useSyncedValue<T>(get: () => T): T {
const nuxt = useNuxtApp()
const synced: any[] = nuxt.payload.state.synced ??= []
if (import.meta.server) {
const value = get()
synced.push(value)
return value
}
if (nuxt.isHydrating) return synced.shift()
return get()
}
const counterKey = Symbol('sync counter')
type SyncedState = any[] & { [counterKey]: number }
export function useSyncedValue<T>(get: () => T): T {
const nuxt = useNuxtApp()
const synced: SyncedState = nuxt.payload.state.synced ??= []
synced[counterKey] ??= 0
if (import.meta.server) return synced[synced[counterKey]++] = get()
if (nuxt.isHydrating) return synced[synced[counterKey]++]
return get()
}
this way the data isnt removed from the array
you should use the useState composable but does basically what you have
yea true
but it requires an explicit key which isnt very great
ideally if im hydrating correctly the order of each hook call will all be the same