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

useLiveQuery.ts

287 lines8.2 KB

1import { useLayoutEffect, useRef, useState } from 'preact/hooks'
2import {
3 createLiveQueryObserver,
4 createLiveQuerySourceIdClaims,
5 getLiveQueryHash,
6 getLiveQueryKey,
7 identifyLiveQuery,
8 isCollection,
9 prepareLiveQueryValue,
10 resolveLiveQueryValue,
11} from '@tanstack/db'
12import type {
13 Collection,
14 CollectionStatus,
15 Context,
16 GetResult,
17 InferResultType,
18 InitialQueryBuilder,
19 LiveQueryCollectionConfig,
20 LiveQueryKey,
21 LiveQueryObserver,
22 LiveQuerySourceIdClaims,
23 LiveQueryStatusFlags,
24 NonSingleResult,
25 PooledLiveQueries,
26 QueryBuilder,
27 SingleResult,
28} from '@tanstack/db'
29​
30// A live query this hook creates from a callback or config retires 1 ms after
31// its last subscriber leaves. A supplied Collection, or a config with an
32// explicit `gcTime`, keeps the caller's retention policy.
33const DEFAULT_GC_TIME_MS = 1
34​
35export type UseLiveQueryStatus = CollectionStatus | `disabled`
36​
37type ConfiguredQueryBuilder<TContext extends Context> = Extract<
38 LiveQueryCollectionConfig<TContext>[`query`],
39 QueryBuilder<TContext>
41​
42type UseLiveQueryConfigOptions<TContext extends Context> = Omit<
43 LiveQueryCollectionConfig<TContext>,
44 `query`
45> & {
46 /**
47 * Explicit identity for a query whose IR cannot derive one, such as a query
48 * with functional variants. Structured queries should omit it.
49 */
50 queryKey?: LiveQueryKey
51 /**
52 * Pass `pooledLiveQueries` to share one partition among equality-filtered
53 * queries of one shape.
54 */
55 pool?: PooledLiveQueries
57​
58export type UseLiveQueryConfig<TContext extends Context> =
59 UseLiveQueryConfigOptions<TContext> &
60 Pick<LiveQueryCollectionConfig<TContext>, `query`>
61​
62export type ConditionalUseLiveQueryConfig<TContext extends Context> =
63 UseLiveQueryConfigOptions<TContext> & {
64 query:
65 | ConfiguredQueryBuilder<TContext>
66 | ((
67 q: InitialQueryBuilder,
68 ) => ConfiguredQueryBuilder<TContext> | undefined | null)
69 }
70​
71/** The result of a live query that is always enabled. */
72export interface UseLiveQueryResult<
73 TResult extends object,
74 TKey extends string | number,
75 TData,
76 TCollection,
77> extends LiveQueryStatusFlags {
78 state: ReadonlyMap<TKey, TResult>
79 data: TData
80 collection: TCollection
81 status: CollectionStatus
82 isEnabled: true
84​
85/** The result of a live query whose callback can disable it. */
86export interface UseConditionalLiveQueryResult<
87 TResult extends object,
88 TKey extends string | number,
89 TData,
90 TCollection,
91> extends LiveQueryStatusFlags {
92 state: ReadonlyMap<TKey, TResult> | undefined
93 data: TData | undefined
94 collection: TCollection | undefined
95 status: UseLiveQueryStatus
96 isEnabled: boolean
98​
99type QueryResult<TContext extends Context> = UseLiveQueryResult<
100 GetResult<TContext>,
101 string | number,
102 InferResultType<TContext>,
103 Collection<GetResult<TContext>, string | number, {}>
105​
106type ConditionalQueryResult<TContext extends Context> =
107 UseConditionalLiveQueryResult<
108 GetResult<TContext>,
109 string | number,
110 InferResultType<TContext>,
111 Collection<GetResult<TContext>, string | number, {}>
112 >
113​
114/**
115 * Subscribe a Preact component to a live query.
116 *
117 * The hook derives the query's identity from its structured IR on each render,
118 * so values captured by the callback recompile the query when they change. A
119 * query whose IR cannot be hashed, such as one using `fn.where`, throws
120 * `UnhashableQueryIRError` unless its config supplies `queryKey`. While the
121 * hook is mounted, each Collection ID its queries read must keep naming one
122 * source object, or it throws `SourceCollectionIdReuseError`.
123 * Return `undefined` or `null` from the callback to disable the query.
124 *
125 * @example
126 * const { data, isLoading } = useLiveQuery((q) =>
127 * q
128 * .from({ todos: todosCollection })
129 * .where(({ todos }) => eq(todos.completed, false)),
130 * )
131 *
132 * @example
133 * // Disable the query until its input exists
134 * const { data, isEnabled } = useLiveQuery((q) =>
135 * userId
136 * ? q
137 * .from({ todos: todosCollection })
138 * .where(({ todos }) => eq(todos.userId, userId))
139 * : undefined,
140 * )
141 */
142export function useLiveQuery<TContext extends Context>(
143 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
144): QueryResult<TContext>
145​
146export function useLiveQuery<TContext extends Context>(
147 queryFn: (
148 q: InitialQueryBuilder,
149 ) => QueryBuilder<TContext> | undefined | null,
150): ConditionalQueryResult<TContext>
151​
152export function useLiveQuery<TContext extends Context>(
153 queryFn: (
154 q: InitialQueryBuilder,
155 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
156): ConditionalQueryResult<TContext>
157​
158export function useLiveQuery<
159 TResult extends object,
160 TKey extends string | number,
161 TUtils extends Record<string, any>,
162>(
163 queryFn: (
164 q: InitialQueryBuilder,
165 ) => Collection<TResult, TKey, TUtils> | undefined | null,
166): UseConditionalLiveQueryResult<
167 TResult,
168 TKey,
169 Array<TResult>,
170 Collection<TResult, TKey, TUtils>
172​
173/**
174 * Subscribe to a live query described by a config object.
175 *
176 * @example
177 * const { data } = useLiveQuery({
178 * query: (q) => q.from({ todos: todosCollection }),
179 * gcTime: 60_000,
180 * })
181 */
182export function useLiveQuery<TContext extends Context>(
183 config: UseLiveQueryConfig<TContext>,
184): QueryResult<TContext>
185​
186export function useLiveQuery<TContext extends Context>(
187 config: ConditionalUseLiveQueryConfig<TContext>,
188): ConditionalQueryResult<TContext>
189​
190/**
191 * Subscribe to an existing live-query Collection. The hook starts its sync and
192 * leaves its retention policy to the caller.
193 *
194 * @example
195 * const activeTodos = createLiveQueryCollection((q) =>
196 * q.from({ todos: todosCollection }).where(({ todos }) => todos.active),
197 * )
198 * const { data, collection } = useLiveQuery(activeTodos)
199 */
200export function useLiveQuery<
201 TResult extends object,
202 TKey extends string | number,
203 TUtils extends Record<string, any>,
204>(
205 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
206): UseLiveQueryResult<
207 TResult,
208 TKey,
209 Array<TResult>,
210 Collection<TResult, TKey, TUtils>
212​
213export function useLiveQuery<
214 TResult extends object,
215 TKey extends string | number,
216 TUtils extends Record<string, any>,
217>(
218 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
219): UseLiveQueryResult<
220 TResult,
221 TKey,
222 TResult | undefined,
223 Collection<TResult, TKey, TUtils> & SingleResult
225​
226export function useLiveQuery(
227 input: unknown,
228): UseConditionalLiveQueryResult<
229 object,
230 string | number,
231 unknown,
232 Collection<object, string | number, any>
233> {
234 const claimsRef = useRef<LiveQuerySourceIdClaims | null>(null)
235 const preparedValue = prepareLiveQueryValue(input, undefined)
236 const queryKey = getLiveQueryKey(input)
237 // A supplied Collection is not compiled, so its object is its identity.
238 const identity = isCollection(input)
239 ? input
240 : queryKey
241 ? getLiveQueryHash(preparedValue, queryKey)
242 : identifyLiveQuery(
243 preparedValue,
244 {
245 claims: (claimsRef.current ??= createLiveQuerySourceIdClaims()),
246 client: undefined,
247 bindingName: `useLiveQuery`,
248 },
249 getLiveQueryHash,
250 )
251​
252 const bindingRef = useRef<LiveQueryBinding | null>(null)
253 let binding = bindingRef.current
254 if (binding?.identity !== identity) {
255 binding = bindingRef.current = {
256 identity,
257 // Wholesale mode publishes nothing during subscribe; the hook re-reads
258 // the observer's snapshot on each notification.
259 observer: createLiveQueryObserver(
260 resolveLiveQueryValue(preparedValue, { gcTime: DEFAULT_GC_TIME_MS }),
261 { mode: `wholesale` },
262 ),
263 }
264 }
265​
266 const { observer } = binding
267 const snapshot = observer.getSnapshot()
268 const [, setRevision] = useState(0)
269​
270 useLayoutEffect(() => {
271 const rerender = () => setRevision((revision) => revision + 1)
272 observer.subscribe(rerender)
273 // The query can publish between this render and its subscription.
274 if (observer.getSnapshot() !== snapshot) rerender()
275 // Each binding owns its observer, so disposal also detaches this
276 // subscription and releases the live-query Collection.
277 return () => observer.dispose()
278 }, [observer])
279​
280 return snapshot
282​
283/** The live query one hook instance reads until its identity changes. */
284interface LiveQueryBinding {
285 identity: unknown
286 observer: LiveQueryObserver<object, string | number>