Skip to content

Instantly share code, notes, and snippets.

@DarkRoku12
Last active December 25, 2023 02:18
Show Gist options
  • Save DarkRoku12/106c6d3d104c5d6c81175df989c5c900 to your computer and use it in GitHub Desktop.
Save DarkRoku12/106c6d3d104c5d6c81175df989c5c900 to your computer and use it in GitHub Desktop.
Reach hook: useWatched
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