UNPKG

react-granular-store

Version:

Granular react store for subscribing to specific parts of a state tree

39 lines (37 loc) 2.49 kB
type StateTree = Record<string | number | symbol, any>; interface StoreOptions<State extends StateTree> { equalityFn?: <Key extends keyof State>(oldValue: State[Key], newValue: State[Key], key: Key) => boolean; batchUpdates?: boolean; } type SetStateArgument<T> = T | ((prev: T) => T); declare class Store<State extends StateTree> { state: State; options: Required<StoreOptions<State>>; callbacks: { [key in keyof State]?: Set<(newValue: State[key]) => void>; }; private _deferredState; private _awaitingUpdate; constructor(defaultValues: State, options?: StoreOptions<State>); getState<Key extends keyof State>(key: Key): State[Key]; setState<Key extends keyof State>(key: Key, newValue: SetStateArgument<State[Key]>): void; on<Key extends keyof State>(key: Key, callback: (newValue: State[Key]) => void): void; off<Key extends keyof State>(key: Key, callback: (newValue: State[Key]) => void): void; subscribe<Key extends keyof State>(key: Key, callback: (newValue: State[Key]) => void): () => void; private _setState; private _resolveNewValue; private _flagDeferredStateForResolution; private _resolveDeferredState; } declare function useStoreValue<State extends StateTree, Key extends keyof State>(store: Store<State>, key: Key): State[Key]; declare function useStoreValue<State extends StateTree, Key extends keyof State>(store: Store<State> | null, key: Key): State[Key] | null; declare function useStoreUpdate<State extends StateTree, Key extends keyof State>(store: Store<State>, key: Key): (newValue: SetStateArgument<State[Key]>) => void; declare function useStoreUpdate<State extends StateTree, Key extends keyof State>(store: Store<State> | null, key: Key): (newValue: SetStateArgument<State[Key]>) => void; declare function useStoreState<State extends StateTree, Key extends keyof State>(store: Store<State>, key: Key): [State[Key], (newValue: SetStateArgument<State[Key]>) => void]; declare function useStoreState<State extends StateTree, Key extends keyof State>(store: Store<State> | null, key: Key): [State[Key] | null, (newValue: SetStateArgument<State[Key]>) => void]; interface RecordStoreState<T> { [key: string | number | symbol]: T | undefined; } declare class RecordStore<T> extends Store<RecordStoreState<T>> { } export { RecordStore, type RecordStoreState, type SetStateArgument, type StateTree, type StoreOptions, Store as default, useStoreState, useStoreUpdate, useStoreValue };