Open History to see the last commit
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 LiveQueryPersistedStatus,
23 LiveQuerySourceIdClaims,
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>
40>
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
56}
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
71interface LiveQueryResultFlags {
72 isLoading: boolean
73 isReady: boolean
74 persistedStatus: LiveQueryPersistedStatus
75 isPersistedReady: boolean
76 persistedError: unknown | undefined
77 isIdle: boolean
78 isError: boolean
79 isCleanedUp: boolean
80}
81
82/** The result of a live query that is always enabled. */
83export interface UseLiveQueryResult<
84 TResult extends object,
85 TKey extends string | number,
86 TData,
87 TCollection,
88> extends LiveQueryResultFlags {
89 state: ReadonlyMap<TKey, TResult>
90 data: TData
91 collection: TCollection
92 status: CollectionStatus
93 isEnabled: true
94}
95
96/** The result of a live query whose callback can disable it. */
97export interface UseConditionalLiveQueryResult<
98 TResult extends object,
99 TKey extends string | number,
100 TData,
101 TCollection,
102> extends LiveQueryResultFlags {
103 state: ReadonlyMap<TKey, TResult> | undefined
104 data: TData | undefined
105 collection: TCollection | undefined
106 status: UseLiveQueryStatus
107 isEnabled: boolean
108}
109
110type QueryResult<TContext extends Context> = UseLiveQueryResult<
111 GetResult<TContext>,
112 string | number,
113 InferResultType<TContext>,
114 Collection<GetResult<TContext>, string | number, {}>
115>
116
117type ConditionalQueryResult<TContext extends Context> =
118 UseConditionalLiveQueryResult<
119 GetResult<TContext>,
120 string | number,
121 InferResultType<TContext>,
122 Collection<GetResult<TContext>, string | number, {}>
123 >
124
125/**
126 * Subscribe a Preact component to a live query.
127 *
128 * The hook derives the query's identity from its structured IR on each render,
129 * so values captured by the callback recompile the query when they change. A
130 * query whose IR cannot be hashed, such as one using `fn.where`, throws
131 * `UnhashableQueryIRError` unless its config supplies `queryKey`. While the
132 * hook is mounted, each Collection ID its queries read must keep naming one
133 * source object, or it throws `SourceCollectionIdReuseError`.
134 * Return `undefined` or `null` from the callback to disable the query.
135 *
136 * @example
137 * const { data, isLoading } = useLiveQuery((q) =>
138 * q
139 * .from({ todos: todosCollection })
140 * .where(({ todos }) => eq(todos.completed, false)),
141 * )
142 *
143 * @example
144 * // Disable the query until its input exists
145 * const { data, isEnabled } = useLiveQuery((q) =>
146 * userId
147 * ? q
148 * .from({ todos: todosCollection })
149 * .where(({ todos }) => eq(todos.userId, userId))
150 * : undefined,
151 * )
152 */
153export function useLiveQuery<TContext extends Context>(
154 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
155): QueryResult<TContext>
156
157export function useLiveQuery<TContext extends Context>(
158 queryFn: (
159 q: InitialQueryBuilder,
160 ) => QueryBuilder<TContext> | undefined | null,
161): ConditionalQueryResult<TContext>
162
163export function useLiveQuery<TContext extends Context>(
164 queryFn: (
165 q: InitialQueryBuilder,
166 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
167): ConditionalQueryResult<TContext>
168
169export function useLiveQuery<
170 TResult extends object,
171 TKey extends string | number,
172 TUtils extends Record<string, any>,
173>(
174 queryFn: (
175 q: InitialQueryBuilder,
176 ) => Collection<TResult, TKey, TUtils> | undefined | null,
177): UseConditionalLiveQueryResult<
178 TResult,
179 TKey,
180 Array<TResult>,
181 Collection<TResult, TKey, TUtils>
182>
183
184/**
185 * Subscribe to a live query described by a config object.
186 *
187 * @example
188 * const { data } = useLiveQuery({
189 * query: (q) => q.from({ todos: todosCollection }),
190 * gcTime: 60_000,
191 * })
192 */
193export function useLiveQuery<TContext extends Context>(
194 config: UseLiveQueryConfig<TContext>,
195): QueryResult<TContext>
196
197export function useLiveQuery<TContext extends Context>(
198 config: ConditionalUseLiveQueryConfig<TContext>,
199): ConditionalQueryResult<TContext>
200
201/**
202 * Subscribe to an existing live-query Collection. The hook starts its sync and
203 * leaves its retention policy to the caller.
204 *
205 * @example
206 * const activeTodos = createLiveQueryCollection((q) =>
207 * q.from({ todos: todosCollection }).where(({ todos }) => todos.active),
208 * )
209 * const { data, collection } = useLiveQuery(activeTodos)
210 */
211export function useLiveQuery<
212 TResult extends object,
213 TKey extends string | number,
214 TUtils extends Record<string, any>,
215>(
216 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
217): UseLiveQueryResult<
218 TResult,
219 TKey,
220 Array<TResult>,
221 Collection<TResult, TKey, TUtils>
222>
223
224export function useLiveQuery<
225 TResult extends object,
226 TKey extends string | number,
227 TUtils extends Record<string, any>,
228>(
229 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
230): UseLiveQueryResult<
231 TResult,
232 TKey,
233 TResult | undefined,
234 Collection<TResult, TKey, TUtils> & SingleResult
235>
236
237export function useLiveQuery(
238 input: unknown,
239): UseConditionalLiveQueryResult<
240 object,
241 string | number,
242 unknown,
243 Collection<object, string | number, any>
244> {
245 const claimsRef = useRef<LiveQuerySourceIdClaims | null>(null)
246 const preparedValue = prepareLiveQueryValue(input, undefined)
247 const queryKey = getLiveQueryKey(input)
248 // A supplied Collection is not compiled, so its object is its identity.
249 const identity = isCollection(input)
250 ? input
251 : queryKey
252 ? getLiveQueryHash(preparedValue, queryKey)
253 : identifyLiveQuery(
254 preparedValue,
255 {
256 claims: (claimsRef.current ??= createLiveQuerySourceIdClaims()),
257 client: undefined,
258 bindingName: `useLiveQuery`,
259 },
260 getLiveQueryHash,
261 )
262
263 const bindingRef = useRef<LiveQueryBinding | null>(null)
264 let binding = bindingRef.current
265 if (binding?.identity !== identity) {
266 binding = bindingRef.current = {
267 identity,
268 // Wholesale mode publishes nothing during subscribe; the hook re-reads
269 // the observer's snapshot on each notification.
270 observer: createLiveQueryObserver(
271 resolveLiveQueryValue(preparedValue, { gcTime: DEFAULT_GC_TIME_MS }),
272 { mode: `wholesale` },
273 ),
274 }
275 }
276
277 const { observer } = binding
278 const snapshot = observer.getSnapshot()
279 const [, setRevision] = useState(0)
280
281 useLayoutEffect(() => {
282 const rerender = () => setRevision((revision) => revision + 1)
283 observer.subscribe(rerender)
284 // The query can publish between this render and its subscription.
285 if (observer.getSnapshot() !== snapshot) rerender()
286 // Each binding owns its observer, so disposal also detaches this
287 // subscription and releases the live-query Collection.
288 return () => observer.dispose()
289 }, [observer])
290
291 return snapshot
292}
293
294/** The live query one hook instance reads until its identity changes. */
295interface LiveQueryBinding {
296 identity: unknown
297 observer: LiveQueryObserver<object, string | number>
298}