Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

Subscribe.public.ts

40 lines1.3 KB

1import { shallow, useSelector } from '@tanstack/solid-store'
2import { createMemo } from 'solid-js'
3import type { Accessor, JSX } from 'solid-js'
4import type {
5 Atom,
6 ReadonlyAtom,
7 ReadonlyStore,
8 Store,
9} from '@tanstack/solid-store'
10​
11export type SubscribeSource<TValue> =
12 Atom<TValue> | ReadonlyAtom<TValue> | Store<TValue> | ReadonlyStore<TValue>
13​
14export interface SubscribeProps<TSourceData, TSelected> {
15 source: SubscribeSource<TSourceData>
16 selector: (state: TSourceData) => TSelected
17 when?: (selected: NoInfer<TSelected>) => boolean
18 children: ((state: Accessor<NoInfer<TSelected>>) => JSX.Element) | JSX.Element
20​
21/** Subscribe to a TanStack Store source and expose the selection as an accessor. */
22export function Subscribe<TSourceData, const TSelected>(
23 props: SubscribeProps<TSourceData, TSelected>,
24): JSX.Element {
25 const selected = useSelector(props.source, props.selector, {
26 compare: shallow,
27 })
28 let child: JSX.Element
29 let initialized = false
30​
31 return createMemo(() => {
32 if (props.when?.(selected()) === false) return null
33 if (!initialized) {
34 const children = props.children
35 child = typeof children === 'function' ? children(selected) : children
36 initialized = true
37 }
38 return child
39 }) as unknown as JSX.Element