Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useStore function in @lefun/ui #17

Merged
merged 1 commit into from
Jul 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion packages/ui/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export type MatchState<B, PB = EmptyObject> = _MatchState<B, PB> & {

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

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

export const storeContext = createContext<Store | null>(null);
Expand Down Expand Up @@ -209,3 +208,22 @@ export const useUsernames = <B, PB>(): Record<UserId, string> => {
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<B, PB>() {
const store = useContext(storeContext) as Store<B, PB>;
if (store === null) {
throw new Error("Store is `null`, did you forget <storeContext.Provider>?");
}
return store;
}

/* Convenience function to get a typed `useStore` hook. */
export const makeUseStore = <B, PB = EmptyObject>() => useStore<B, PB>;