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

(BSR) feat(Zustand): Simplify selectors #7520

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: add selector hooks generator
xlecunff-pass committed Jan 14, 2025
commit cca676d300daa7c8a954a65734e1f88fdc36eab0
22 changes: 21 additions & 1 deletion src/libs/store/createStore.ts
Original file line number Diff line number Diff line change
@@ -3,7 +3,13 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
import { create } from 'zustand'
import { createJSONStorage, devtools, persist } from 'zustand/middleware'

import { AnyFunction, CurriedAnyFunction, StoreConfig, Store } from './store.types'
import {
AnyFunction,
CurriedAnyFunction,
StoreConfig,
Store,
ReplaceSelectByUse,
} from './store.types'

export function createStore<
State,
@@ -49,11 +55,25 @@ export function createStore<
}
)

const hooks = Object.entries(selectors).reduce(
(acc, [key, selector]) => ({
...acc,
[key.replace('select', 'use')]: (...args: Parameters<typeof selector>) =>
store((state) => selector(...args)(state)),
xlecunff-pass marked this conversation as resolved.
Show resolved Hide resolved
}),
{} as {
[K in keyof Selectors as ReplaceSelectByUse<string & K>]: (
...args: Parameters<Selectors[K]>
) => ReturnType<ReturnType<Selectors[K]>>
}
)

return {
useStore: store,
actions,
selectors: selectorsWithState,
select,
hooks,
}
}

12 changes: 11 additions & 1 deletion src/libs/store/store.types.ts
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ export type CurriedAnyFunction<State> = (...args: never[]) => (state: State) =>
type Options = {
persist?: boolean
}
export type ReplaceSelectByUse<T extends string> = T extends `select${infer U}` ? `use${U}` : never
type StoreType<State> = UseBoundStore<StoreApi<State>>
export type StoreConfig<
State,
@@ -32,6 +33,15 @@ export type Store<
> = {
useStore: UseBoundStore<StoreApi<State>>
actions: Actions
selectors: SelectorsWithState<State, Selectors>
selectors: {
[K in keyof Selectors]: (
...args: Parameters<Selectors[K]>
) => ReturnType<ReturnType<Selectors[K]>>
}
select: <T>(selector: (state: State) => T) => T
hooks: {
[K in keyof Selectors as ReplaceSelectByUse<string & K>]: (
...args: Parameters<Selectors[K]>
) => ReturnType<ReturnType<Selectors[K]>>
}
}