Open History to see the last commit
1import { shallow, useSelector } from '@tanstack/preact-store'
2import type {
3 Atom,
4 ReadonlyAtom,
5 ReadonlyStore,
6 Store,
7} from '@tanstack/preact-store'
8import type { CrossVersionPreactNode } from './preactTypes.public'
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:
29 | ((state: NoInfer<TSelected>) => CrossVersionPreactNode)
30 | CrossVersionPreactNode
31}
32β
33/**
34 * A Preact component that allows you to subscribe to source state.
35 *
36 * This is useful for opting into state re-renders for specific parts of the state.
37 */
38export function Subscribe<TSourceData, const TSelected>(
39 props: SubscribeProps<TSourceData, TSelected>,
40): CrossVersionPreactNode {
41 const selected = useSelector(
42 // Atom and store share the same selection protocol; union args need a widen for TS.
43 props.source,
44 props.selector as Parameters<typeof useSelector>[1],
45 {
46 compare: shallow,
47 },
48 ) as TSelected
49β
50 if (props.when?.(selected) === false) {
51 return null
52 }
53 return typeof props.children === 'function'
54 ? props.children(selected)
55 : props.children
56}