Last active
December 25, 2023 02:18
-
-
Save DarkRoku12/106c6d3d104c5d6c81175df989c5c900 to your computer and use it in GitHub Desktop.
Reach hook: useWatched
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
import { SymbolAddWatcher, SymbolForAll, Watched } from "./constants"; | |
export type RecordIndex = string | number | symbol; | |
export type AnyRecord = Record<RecordIndex, any>; | |
export type RecordObj<T extends AnyRecord> = T & AnyRecord; | |
export default function useWatched<T extends AnyRecord>( | |
watched: Watched<T>, | |
watchList: Array<keyof T> | Array<string | symbol> = [SymbolForAll], | |
onChance?: (updated: Partial<RecordObj<T>>) => void | |
) { | |
const [, setter] = useState(watched); | |
for (const key of watchList) { | |
// prettier-ignore | |
const cb = onChance ? (v: any) => { setter(v); onChance(v); } : setter; | |
watched[SymbolAddWatcher](key, cb); | |
} | |
return watched; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires: