docs(auto-generating-selectors): Add vanilla store variant (#1915)

* Add variant for vanilla stores

* Update text tone and style

Co-authored-by: Blazej Sewera <code@sewera.dev>

* Adjust code style to match zustand's one

* Run prettier

---------

Co-authored-by: Blazej Sewera <code@sewera.dev>
This commit is contained in:
Luiz Felicio 2023-07-04 20:38:35 -03:00 committed by GitHub
parent ea40986e46
commit 808a72225e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -65,6 +65,63 @@ const bears = useBearStore.use.bears()
const increment = useBearStore.use.increment()
```
## Vanilla Store
If you are using a vanilla store, use the following `createSelectors` function:
```typescript
import { StoreApi, useStore } from 'zustand'
type WithSelectors<S> = S extends { getState: () => infer T }
? S & { use: { [K in keyof T]: () => T[K] } }
: never
const createSelectors = <S extends StoreApi<object>>(_store: S) => {
const store = _store as WithSelectors<typeof _store>
store.use = {}
for (const k of Object.keys(store.getState())) {
;(store.use as any)[k] = () =>
useStore(_store, (s) => s[k as keyof typeof s])
}
return store
}
```
The usage is the same as a React store. If you have a store like this:
```typescript
import { createStore } from 'zustand'
interface BearState {
bears: number
increase: (by: number) => void
increment: () => void
}
const store = createStore<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:
```typescript
const useBearStore = createSelectors(store)
```
Now the selectors are auto generated and you can access them directly:
```typescript
// get the property
const bears = useBearStore.use.bears()
// get the action
const increment = useBearStore.use.increment()
```
## Live Demo
For a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).