fix(docs): Auto generating selectors docs updated to match v4 syntax (#1079)

* Auto generating selectors updated to match v4 syntax

* Update docs/auto-generating-selectors.md

Co-authored-by: Devansh Jethmalani <jethmalani.devansh@gmail.com>

* Updated type declaration for createSelectors

* Update docs/auto-generating-selectors.md

* run prettier

Co-authored-by: Devansh Jethmalani <jethmalani.devansh@gmail.com>
Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
Co-authored-by: daishi <daishi@axlight.com>
This commit is contained in:
Janis Jansen 2022-07-18 01:52:51 +02:00 committed by GitHub
parent ef46c68641
commit 15ff6623c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -13,25 +13,20 @@ However, writing these could be tedious, but you can auto-generate them
```typescript
import { State, StoreApi, UseBoundStore } from 'zustand'
interface Selectors<StoreType> {
use: {
[key in keyof StoreType]: () => StoreType[key]
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])
}
}
export default function createSelectors<StoreType extends State>(
store: UseBoundStore<StoreType, StoreApi<StoreType>>
) {
// Casting to any to allow adding a new property
;(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 UseBoundStore<StoreType, StoreApi<StoreType>> &
Selectors<StoreType>
return store
}
```
@ -44,10 +39,10 @@ interface BearState {
increment: () => void
}
const useStoreBase = create<BearState>((set) => ({
const useStoreBase = create<BearState>()((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
increment: () => set((state) => state.increase(1)),
increment: () => set((state) => ({ bears: state.bears + 1 })),
}))
```