zustand/docs/auto-generating-selectors.md
Daishi Kato fa581ddd9b
fix(docs): useBoundStore instead of useStore (#1125)
* fix(docs): useBoundStore instead of useStore

* run prettier
2022-07-26 08:58:43 +09:00

1.8 KiB

Auto Generating Selectors

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 { State, StoreApi, UseBoundStore } from 'zustand'

type WithSelectors<S> = S extends { getState: () => infer T }
  ? S & { use: { [K in keyof T]: () => T[K] } }
  : never

const createSelectors = <S extends UseBoundStore<StoreApi<State>>>(
  _store: S
) => {
  let store = _store as WithSelectors<typeof _store>
  store.use = {}
  for (let k of Object.keys(store.getState())) {
    ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])
  }

  return store
}

If you have a store like this:

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

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

Apply that function to your store:

const useBearStore = createSelectors(useBearStoreBase)

Now the selectors are auto generated:

// get the property
const bears = useBearStore.use.bears()

// get the action
const increase = useBearStore.use.increment()

Live Demo

for a working example of this, see the Code Sandbox

3rd-party Libraries