Skip to content
Myr

subscribeWithSelector.ts

This file

Path

src/middleware/subscribeWithSelector.ts

73 lines · 2.4 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f85898f point at it.

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 1–73why, one step back
1import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'
23type SubscribeWithSelector = <4 T,5 Mps extends [StoreMutatorIdentifier, unknown][] = [],6 Mcs extends [StoreMutatorIdentifier, unknown][] = [],7>(8 initializer: StateCreator<9 T,10 [...Mps, ['zustand/subscribeWithSelector', never]],11 Mcs12 >,13) => StateCreator<T, Mps, [['zustand/subscribeWithSelector', never], ...Mcs]>1415type Write<T, U> = Omit<T, keyof U> & U1617type WithSelectorSubscribe<S> = S extends { getState: () => infer T }18 ? Write<S, StoreSubscribeWithSelector<T>>19 : never2021declare module '../vanilla' {22 // eslint-disable-next-line @typescript-eslint/no-unused-vars23 interface StoreMutators<S, A> {24 ['zustand/subscribeWithSelector']: WithSelectorSubscribe<S>25 }26}2728type StoreSubscribeWithSelector<T> = {29 subscribe: {30 (listener: (selectedState: T, previousSelectedState: T) => void): () => void31 <U>(32 selector: (state: T) => U,33 listener: (selectedState: U, previousSelectedState: U) => void,34 options?: {35 equalityFn?: (a: U, b: U) => boolean36 fireImmediately?: boolean37 },38 ): () => void39 }40}4142type SubscribeWithSelectorImpl = <T extends object>(43 storeInitializer: StateCreator<T, [], []>,44) => StateCreator<T, [], []>4546const subscribeWithSelectorImpl: SubscribeWithSelectorImpl =47 (fn) => (set, get, api) => {48 type S = ReturnType<typeof fn>49 type Listener = (state: S, previousState: S) => void50 const origSubscribe = api.subscribe as (listener: Listener) => () => void51 api.subscribe = ((selector: any, optListener: any, options: any) => {52 let listener: Listener = selector // if no selector53 if (optListener) {54 const equalityFn = options?.equalityFn || Object.is55 let currentSlice = selector(api.getState())56 listener = (state) => {57 const nextSlice = selector(state)58 if (!equalityFn(currentSlice, nextSlice)) {59 const previousSlice = currentSlice60 optListener((currentSlice = nextSlice), previousSlice)61 }62 }63 if (options?.fireImmediately) {64 optListener(currentSlice, currentSlice)65 }66 }67 return origSubscribe(listener)68 }) as any69 const initialState = fn(set, get, api)70 return initialState71 }72export const subscribeWithSelector =73 subscribeWithSelectorImpl as unknown as SubscribeWithSelector