Skip to content

Commit 41b908e

Browse files
committed
Add useStore function in @lefun/ui
1 parent faeeb93 commit 41b908e

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

packages/ui/src/index.tsx

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ export type MatchState<B, PB = EmptyObject> = _MatchState<B, PB> & {
1616

1717
export type Selector<T, B, PB = EmptyObject> = (state: MatchState<B, PB>) => T;
1818

19-
// TODO Type this properly
2019
export type Store<B = unknown, PB = unknown> = StoreApi<MatchState<B, PB>>;
2120

2221
export const storeContext = createContext<Store | null>(null);
@@ -209,3 +208,22 @@ export const useUsernames = <B, PB>(): Record<UserId, string> => {
209208
export const useMyUserId = () => {
210209
return useSelector((state) => state.userId);
211210
};
211+
212+
/* Return the store object.
213+
*
214+
* This is useful to access the state without subscribing to changes:
215+
* ```
216+
* const store = useStore()
217+
* const x = store.getState().board.x
218+
* ```
219+
* */
220+
export function useStore<B, PB>() {
221+
const store = useContext(storeContext) as Store<B, PB>;
222+
if (store === null) {
223+
throw new Error("Store is `null`, did you forget <storeContext.Provider>?");
224+
}
225+
return store;
226+
}
227+
228+
/* Convenience function to get a typed `useStore` hook. */
229+
export const makeUseStore = <B, PB = EmptyObject>() => useStore<B, PB>;

0 commit comments

Comments
 (0)