Skip to content

Instantly share code, notes, and snippets.

@adicuco
Last active July 16, 2024 09:56
Show Gist options
  • Select an option

  • Save adicuco/22d86cdce08d5e9dddada3d25abf6a6c to your computer and use it in GitHub Desktop.

Select an option

Save adicuco/22d86cdce08d5e9dddada3d25abf6a6c to your computer and use it in GitHub Desktop.
Zustand Automatically Generated Hooks & Get Selectors
import { type StoreApi, useStore } from "zustand";
type WithHookSelectors<S> = S extends { getState: () => infer T }
? S & { use: { [K in keyof T]: () => T[K] } }
: never;
export function createHookSelectors<S extends StoreApi<object>>(_store: S) {
const store = _store as WithHookSelectors<typeof _store>;
store.use = {};
for (const key of Object.keys(store.getState())) {
(store.use as any)[key] = () =>
useStore(_store, (s) => s[key as keyof typeof s]);
}
return store;
}
type GetRecord<O> = {
[K in keyof O]: (equalityFn?: (a: O[K], b: O[K]) => boolean) => O[K];
};
type WithGetSelectors<S> = S extends { getState: () => infer T }
? S & { get: GetRecord<T> }
: never;
export function createGetSelectors<S extends StoreApi<object>>(_store: S) {
const store = _store as WithGetSelectors<typeof _store>;
store.get = {} as GetRecord<typeof store.getState>;
for (const key of Object.keys(store.getState())) {
(store.get as any)[key] = () =>
store.getState()[key as keyof typeof store.getState];
}
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment