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

Migrate docs from wiki: auto generating selectors #1057

Merged
merged 7 commits into from
Jul 11, 2022
Merged
Changes from 2 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
69 changes: 69 additions & 0 deletions docs/auto-generating-selectors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Auto Generating Selectors

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

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

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

## create the following function: `createSelectors`

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

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

function createSelectors<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:

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

const useStoreBase = create<BearState>((set) => ({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const useStoreBase = create<BearState>((set) => ({
const useStoreBase = create<BearState>()((set) => ({

bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}))
```

## Apply that function to your store:

```typescript
const useStore = createSelectors(useStoreBase)
```

## Now the selectors are auto generated:

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

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

## Libraries

- Or you can just `npm i auto-zustand-selectors-hook`
- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)
- [zustood](https://github.com/udecode/zustood)