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

useLiveQuery.ts

349 lines11.2 KB

1import { useRef, useSyncExternalStore } from "react"
2import { createLiveQueryCollection } from "@tanstack/db"
3import type {
4 Collection,
5 CollectionStatus,
6 Context,
7 GetResult,
8 InitialQueryBuilder,
9 LiveQueryCollectionConfig,
10 QueryBuilder,
11} from "@tanstack/db"
12​
13/**
14 * Create a live query using a query function
15 * @param queryFn - Query function that defines what data to fetch
16 * @param deps - Array of dependencies that trigger query re-execution when changed
17 * @returns Object with reactive data, state, and status information
18 * @example
19 * // Basic query with object syntax
20 * const { data, isLoading } = useLiveQuery((q) =>
21 * q.from({ todos: todosCollection })
22 * .where(({ todos }) => eq(todos.completed, false))
23 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
24 * )
25 *
26 * @example
27 * // With dependencies that trigger re-execution
28 * const { data, state } = useLiveQuery(
29 * (q) => q.from({ todos: todosCollection })
30 * .where(({ todos }) => gt(todos.priority, minPriority)),
31 * [minPriority] // Re-run when minPriority changes
32 * )
33 *
34 * @example
35 * // Join pattern
36 * const { data } = useLiveQuery((q) =>
37 * q.from({ issues: issueCollection })
38 * .join({ persons: personCollection }, ({ issues, persons }) =>
39 * eq(issues.userId, persons.id)
40 * )
41 * .select(({ issues, persons }) => ({
42 * id: issues.id,
43 * title: issues.title,
44 * userName: persons.name
45 * }))
46 * )
47 *
48 * @example
49 * // Handle loading and error states
50 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
51 * q.from({ todos: todoCollection })
52 * )
53 *
54 * if (isLoading) return <div>Loading...</div>
55 * if (isError) return <div>Error: {status}</div>
56 *
57 * return (
58 * <ul>
59 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
60 * </ul>
61 * )
62 */
63// Overload 1: Accept just the query function
64export function useLiveQuery<TContext extends Context>(
65 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
66 deps?: Array<unknown>
67): {
68 state: Map<string | number, GetResult<TContext>>
69 data: Array<GetResult<TContext>>
70 collection: Collection<GetResult<TContext>, string | number, {}>
71 status: CollectionStatus
72 isLoading: boolean
73 isReady: boolean
74 isIdle: boolean
75 isError: boolean
76 isCleanedUp: boolean
78​
79/**
80 * Create a live query using configuration object
81 * @param config - Configuration object with query and options
82 * @param deps - Array of dependencies that trigger query re-execution when changed
83 * @returns Object with reactive data, state, and status information
84 * @example
85 * // Basic config object usage
86 * const { data, status } = useLiveQuery({
87 * query: (q) => q.from({ todos: todosCollection }),
88 * gcTime: 60000
89 * })
90 *
91 * @example
92 * // With query builder and options
93 * const queryBuilder = new Query()
94 * .from({ persons: collection })
95 * .where(({ persons }) => gt(persons.age, 30))
96 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
97 *
98 * const { data, isReady } = useLiveQuery({ query: queryBuilder })
99 *
100 * @example
101 * // Handle all states uniformly
102 * const { data, isLoading, isReady, isError } = useLiveQuery({
103 * query: (q) => q.from({ items: itemCollection })
104 * })
105 *
106 * if (isLoading) return <div>Loading...</div>
107 * if (isError) return <div>Something went wrong</div>
108 * if (!isReady) return <div>Preparing...</div>
109 *
110 * return <div>{data.length} items loaded</div>
111 */
112// Overload 2: Accept config object
113export function useLiveQuery<TContext extends Context>(
114 config: LiveQueryCollectionConfig<TContext>,
115 deps?: Array<unknown>
116): {
117 state: Map<string | number, GetResult<TContext>>
118 data: Array<GetResult<TContext>>
119 collection: Collection<GetResult<TContext>, string | number, {}>
120 status: CollectionStatus
121 isLoading: boolean
122 isReady: boolean
123 isIdle: boolean
124 isError: boolean
125 isCleanedUp: boolean
127​
128/**
129 * Subscribe to an existing live query collection
130 * @param liveQueryCollection - Pre-created live query collection to subscribe to
131 * @returns Object with reactive data, state, and status information
132 * @example
133 * // Using pre-created live query collection
134 * const myLiveQuery = createLiveQueryCollection((q) =>
135 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
136 * )
137 * const { data, collection } = useLiveQuery(myLiveQuery)
138 *
139 * @example
140 * // Access collection methods directly
141 * const { data, collection, isReady } = useLiveQuery(existingCollection)
142 *
143 * // Use collection for mutations
144 * const handleToggle = (id) => {
145 * collection.update(id, draft => { draft.completed = !draft.completed })
146 * }
147 *
148 * @example
149 * // Handle states consistently
150 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
151 *
152 * if (isLoading) return <div>Loading...</div>
153 * if (isError) return <div>Error loading data</div>
154 *
155 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
156 */
157// Overload 3: Accept pre-created live query collection
158export function useLiveQuery<
159 TResult extends object,
160 TKey extends string | number,
161 TUtils extends Record<string, any>,
162>(
163 liveQueryCollection: Collection<TResult, TKey, TUtils>
164): {
165 state: Map<TKey, TResult>
166 data: Array<TResult>
167 collection: Collection<TResult, TKey, TUtils>
168 status: CollectionStatus
169 isLoading: boolean
170 isReady: boolean
171 isIdle: boolean
172 isError: boolean
173 isCleanedUp: boolean
175​
176// Implementation - use function overloads to infer the actual collection type
177export function useLiveQuery(
178 configOrQueryOrCollection: any,
179 deps: Array<unknown> = []
180) {
181 // Check if it's already a collection by checking for specific collection methods
182 const isCollection =
183 configOrQueryOrCollection &&
184 typeof configOrQueryOrCollection === `object` &&
185 typeof configOrQueryOrCollection.subscribeChanges === `function` &&
186 typeof configOrQueryOrCollection.startSyncImmediate === `function` &&
187 typeof configOrQueryOrCollection.id === `string`
188​
189 // Use refs to cache collection and track dependencies
190 const collectionRef = useRef<Collection<object, string | number, {}> | null>(
191 null
192 )
193 const depsRef = useRef<Array<unknown> | null>(null)
194 const configRef = useRef<unknown>(null)
195​
196 // Check if we need to create/recreate the collection
197 const needsNewCollection =
198 !collectionRef.current ||
199 (isCollection && configRef.current !== configOrQueryOrCollection) ||
200 (!isCollection &&
201 (depsRef.current === null ||
202 depsRef.current.length !== deps.length ||
203 depsRef.current.some((dep, i) => dep !== deps[i])))
204​
205 if (needsNewCollection) {
206 if (isCollection) {
207 // It's already a collection, ensure sync is started for React hooks
208 configOrQueryOrCollection.startSyncImmediate()
209 collectionRef.current = configOrQueryOrCollection
210 configRef.current = configOrQueryOrCollection
211 } else {
212 // Original logic for creating collections
213 // Ensure we always start sync for React hooks
214 if (typeof configOrQueryOrCollection === `function`) {
215 collectionRef.current = createLiveQueryCollection({
216 query: configOrQueryOrCollection,
217 startSync: true,
218 gcTime: 0, // Live queries created by useLiveQuery are cleaned up immediately
219 }) as unknown as Collection<object, string | number, {}>
220 } else {
221 collectionRef.current = createLiveQueryCollection({
222 startSync: true,
223 gcTime: 0, // Live queries created by useLiveQuery are cleaned up immediately
224 ...configOrQueryOrCollection,
225 }) as unknown as Collection<object, string | number, {}>
226 }
227 depsRef.current = [...deps]
228 }
229 }
230​
231 // Use refs to track version and memoized snapshot
232 const versionRef = useRef(0)
233 const snapshotRef = useRef<{
234 collection: Collection<object, string | number, {}>
235 version: number
236 } | null>(null)
237​
238 // Reset refs when collection changes
239 if (needsNewCollection) {
240 versionRef.current = 0
241 snapshotRef.current = null
242 }
243​
244 // Create stable subscribe function using ref
245 const subscribeRef = useRef<
246 ((onStoreChange: () => void) => () => void) | null
247 >(null)
248 if (!subscribeRef.current || needsNewCollection) {
249 subscribeRef.current = (onStoreChange: () => void) => {
250 const unsubscribe = collectionRef.current!.subscribeChanges(() => {
251 // Bump version on any change; getSnapshot will rebuild next time
252 versionRef.current += 1
253 onStoreChange()
254 })
255 // Collection may be ready and will not receive initial `subscribeChanges()`
256 if (collectionRef.current!.status === `ready`) {
257 versionRef.current += 1
258 onStoreChange()
259 }
260 return () => {
261 unsubscribe()
262 }
263 }
264 }
265​
266 // Create stable getSnapshot function using ref
267 const getSnapshotRef = useRef<
268 | (() => {
269 collection: Collection<object, string | number, {}>
270 version: number
271 })
272 | null
273 >(null)
274 if (!getSnapshotRef.current || needsNewCollection) {
275 getSnapshotRef.current = () => {
276 const currentVersion = versionRef.current
277 const currentCollection = collectionRef.current!
278​
279 // Recreate snapshot object only if version/collection changed
280 if (
281 !snapshotRef.current ||
282 snapshotRef.current.version !== currentVersion ||
283 snapshotRef.current.collection !== currentCollection
284 ) {
285 snapshotRef.current = {
286 collection: currentCollection,
287 version: currentVersion,
288 }
289 }
290​
291 return snapshotRef.current
292 }
293 }
294​
295 // Use useSyncExternalStore to subscribe to collection changes
296 const snapshot = useSyncExternalStore(
297 subscribeRef.current,
298 getSnapshotRef.current
299 )
300​
301 // Track last snapshot (from useSyncExternalStore) and the returned value separately
302 const returnedSnapshotRef = useRef<{
303 collection: Collection<object, string | number, {}>
304 version: number
305 } | null>(null)
306 // Keep implementation return loose to satisfy overload signatures
307 const returnedRef = useRef<any>(null)
308​
309 // Rebuild returned object only when the snapshot changes (version or collection identity)
310 if (
311 !returnedSnapshotRef.current ||
312 returnedSnapshotRef.current.version !== snapshot.version ||
313 returnedSnapshotRef.current.collection !== snapshot.collection
314 ) {
315 // Capture a stable view of entries for this snapshot to avoid tearing
316 const entries = Array.from(snapshot.collection.entries())
317 let stateCache: Map<string | number, unknown> | null = null
318 let dataCache: Array<unknown> | null = null
319​
320 returnedRef.current = {
321 get state() {
322 if (!stateCache) {
323 stateCache = new Map(entries)
324 }
325 return stateCache
326 },
327 get data() {
328 if (!dataCache) {
329 dataCache = entries.map(([, value]) => value)
330 }
331 return dataCache
332 },
333 collection: snapshot.collection,
334 status: snapshot.collection.status,
335 isLoading:
336 snapshot.collection.status === `loading` ||
337 snapshot.collection.status === `initialCommit`,
338 isReady: snapshot.collection.status === `ready`,
339 isIdle: snapshot.collection.status === `idle`,
340 isError: snapshot.collection.status === `error`,
341 isCleanedUp: snapshot.collection.status === `cleaned-up`,
342 }
343​
344 // Remember the snapshot that produced this returned value
345 returnedSnapshotRef.current = snapshot
346 }
347​
348 return returnedRef.current!