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

Subscribe.public.tsx

54 lines1.6 KB

1import { shallow, useSelector } from '@tanstack/react-store'
2import type {
3 Atom,
4 ReadonlyAtom,
5 ReadonlyStore,
6 Store,
7} from '@tanstack/react-store'
8import type { ReactNode } from 'react'
9​
10export type SubscribeSource<TValue> =
11 Atom<TValue> | ReadonlyAtom<TValue> | Store<TValue> | ReadonlyStore<TValue>
12​
13/**
14 * Subscribe to `form.atom` (full form state). The selector receives the full
15 * {@link FormState}.
16 */
17export interface SubscribeProps<in out TSourceData, in out TSelected> {
18 source: SubscribeSource<TSourceData>
19 /**
20 * Select from full form state. Re-renders when the selected value changes
21 * (shallow compare).
22 */
23 selector: (state: TSourceData) => TSelected
24 /**
25 * Optional. If provided, the component will only render when the `when` function returns `true`.
26 */
27 when?: (selected: NoInfer<TSelected>) => boolean
28 children: ((state: NoInfer<TSelected>) => ReactNode) | ReactNode
30​
31/**
32 * A React component that allows you to subscribe to source state.
33 *
34 * This is useful for opting into state re-renders for specific parts of the state.
35 */
36export function Subscribe<TSourceData, const TSelected>(
37 props: SubscribeProps<TSourceData, TSelected>,
38): ReactNode {
39 const selected = useSelector(
40 // Atom and store share the same selection protocol; union args need a widen for TS.
41 props.source,
42 props.selector as Parameters<typeof useSelector>[1],
43 {
44 compare: shallow,
45 },
46 ) as TSelected
47​
48 if (props.when?.(selected) === false) {
49 return null
50 }
51 return typeof props.children === 'function'
52 ? props.children(selected)
53 : props.children