Skip to content

Auto Generating Selectors

AlbertGao edited this page Jun 8, 2021 · 9 revisions

It is recommended to use selectors when using either the properties or actions from the store.

const bears = useBearStore(state => state.bears)

However, writing these could be tedious, but you can auto-generate them

create the following function: createSelectors

import create, { StateCreator, State, StoreApi, UseStore } from 'zustand'

interface Selectors<StoreType> {
  use: {
    [key in keyof StoreType]: () => StoreType[key]
  }
}

function createSelectorHooks<StoreType extends State>(
  store: UseStore<StoreType>,
) {
  ;(store as any).use = {}

  Object.keys(store.getState()).forEach(key => {
    const selector = (state: StoreType) => state[key as keyof StoreType]
    ;(store as any).use[key] = () => store(selector)
  })

  return store as UseStore<StoreType> & Selectors<StoreType>
}

If you have a store like this:

interface BearState {
  bears: number;
  increase: (by: number) => void;
}

const useStoreBase = create<BearState>((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}));

apple that function to your store:

const useStore = createSelectorFunctions(useStoreBase);

Now the selectors are auto generated:

// get the property
const bears = useStore.use.bears();

// get the action
const increase = useStore.use.increase();

Libraries

Clone this wiki locally