From 41b908e87962ae7bebb9a7aa876d526d6d29faea Mon Sep 17 00:00:00 2001 From: Simon Lemieux <1105380+simlmx@users.noreply.github.com> Date: Fri, 5 Jul 2024 01:13:30 +0000 Subject: [PATCH] Add `useStore` function in `@lefun/ui` --- packages/ui/src/index.tsx | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx index 2b130c3..bc77b0c 100644 --- a/packages/ui/src/index.tsx +++ b/packages/ui/src/index.tsx @@ -16,7 +16,6 @@ export type MatchState = _MatchState & { export type Selector = (state: MatchState) => T; -// TODO Type this properly export type Store = StoreApi>; export const storeContext = createContext(null); @@ -209,3 +208,22 @@ export const useUsernames = (): Record => { export const useMyUserId = () => { return useSelector((state) => state.userId); }; + +/* Return the store object. + * + * This is useful to access the state without subscribing to changes: + * ``` + * const store = useStore() + * const x = store.getState().board.x + * ``` + * */ +export function useStore() { + const store = useContext(storeContext) as Store; + if (store === null) { + throw new Error("Store is `null`, did you forget ?"); + } + return store; +} + +/* Convenience function to get a typed `useStore` hook. */ +export const makeUseStore = () => useStore;