import { createSignal, onCleanup } from 'solid-js' import type { Accessor } from 'solid-js' export interface UseSelectorOptions { compare?: (a: TSelected, b: TSelected) => boolean } type SelectionSource = { get: () => T subscribe: (listener: (value: T) => void) => { unsubscribe: () => void } } function defaultCompare(a: T, b: T) { return a === b } /** * Selects a slice of state from an atom or store and subscribes the component * to that selection. * * This is the primary Solid read hook for TanStack Store. It returns a Solid * accessor so consumers can read the selected value reactively. * * Omit the selector to subscribe to the whole value. * * @example * ```tsx * const count = useSelector(counterStore, (state) => state.count) * * return

{count()}

* ``` * * @example * ```tsx * const value = useSelector(countAtom) * ``` */ export function useSelector>( source: SelectionSource, selector: (snapshot: TSource) => TSelected = (s) => s as unknown as TSelected, options?: UseSelectorOptions, ): Accessor { const compare = options?.compare ?? defaultCompare const [signal, setSignal] = createSignal(selector(source.get()), { equals: compare, }) const unsubscribe = source.subscribe((snapshot) => { setSignal(() => selector(snapshot)) }).unsubscribe onCleanup(() => { unsubscribe() }) return signal }