#coordinate random values between ssr and csr

8 messages · Page 1 of 1 (latest)

waxen valve
#

I'm making an easter egg and in a component I'm doing something like ```ts
const willShowEasterEgg = Math.random() > 0.5

but this will re-run during hydration and possibly fall out of sync with SSR, how could I go about this?
waxen valve
#

im toying around with useHydration but i dont think this is exactly what im looking for

waxen valve
#

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()
}
waxen valve
#
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

teal inlet
#

you should use the useState composable but does basically what you have

waxen valve
#

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