mirror of
https://github.com/warmbly/warmbly.git
synced 2026-09-13 08:05:05 +00:00
24 lines
631 B
TypeScript
24 lines
631 B
TypeScript
import { useEffect, useRef } from 'react'
|
|
|
|
function makeSignature<T>(value: T): string {
|
|
return JSON.stringify(value, (_key, v) => {
|
|
if (v instanceof Date) return v.toISOString()
|
|
return v
|
|
})
|
|
}
|
|
|
|
export function useSyncToStore<T>(data: T | undefined, syncFn: (data: T) => void) {
|
|
const syncFnRef = useRef(syncFn)
|
|
const lastSigRef = useRef<string | null>(null)
|
|
syncFnRef.current = syncFn
|
|
|
|
useEffect(() => {
|
|
if (data !== undefined) {
|
|
const nextSig = makeSignature(data)
|
|
if (lastSigRef.current === nextSig) return
|
|
lastSigRef.current = nextSig
|
|
syncFnRef.current(data)
|
|
}
|
|
}, [data])
|
|
}
|