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

uselivequery.md

384 lines7.1 KB

1---
2id: useLiveQuery
3title: useLiveQuery
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8# Function: useLiveQuery()
9​
10## Call Signature
11​
12```ts
13function useLiveQuery<TContext>(queryFn, deps?): object
14```
15​
16Defined in: [useLiveQuery.ts:64](https://github.com/TanStack/db/blob/main/packages/react-db/src/useLiveQuery.ts#L64)
17​
18Create a live query using a query function
19​
20### Type Parameters
21​
22• **TContext** *extends* `Context`
23​
24### Parameters
25​
26#### queryFn
27​
28(`q`) => `QueryBuilder`\<`TContext`\>
29​
30Query function that defines what data to fetch
31​
32#### deps?
33​
34`unknown`[]
35​
36Array of dependencies that trigger query re-execution when changed
37​
38### Returns
39​
40`object`
41​
42Object with reactive data, state, and status information
43​
44#### collection
45​
46```ts
47collection: Collection<{ [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }, string | number, {}>;
48```
49​
50#### data
51​
52```ts
53data: { [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }[];
54```
55​
56#### isCleanedUp
57​
58```ts
59isCleanedUp: boolean;
60```
61​
62#### isError
63​
64```ts
65isError: boolean;
66```
67​
68#### isIdle
69​
70```ts
71isIdle: boolean;
72```
73​
74#### isLoading
75​
76```ts
77isLoading: boolean;
78```
79​
80#### isReady
81​
82```ts
83isReady: boolean;
84```
85​
86#### state
87​
88```ts
89state: Map<string | number, { [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }>;
90```
91​
92#### status
93​
94```ts
95status: CollectionStatus;
96```
97​
98### Examples
99​
100```ts
101// Basic query with object syntax
102const { data, isLoading } = useLiveQuery((q) =>
103 q.from({ todos: todosCollection })
104 .where(({ todos }) => eq(todos.completed, false))
105 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
107```
108​
109```ts
110// With dependencies that trigger re-execution
111const { data, state } = useLiveQuery(
112 (q) => q.from({ todos: todosCollection })
113 .where(({ todos }) => gt(todos.priority, minPriority)),
114 [minPriority] // Re-run when minPriority changes
116```
117​
118```ts
119// Join pattern
120const { data } = useLiveQuery((q) =>
121 q.from({ issues: issueCollection })
122 .join({ persons: personCollection }, ({ issues, persons }) =>
123 eq(issues.userId, persons.id)
124 )
125 .select(({ issues, persons }) => ({
126 id: issues.id,
127 title: issues.title,
128 userName: persons.name
129 }))
131```
132​
133```ts
134// Handle loading and error states
135const { data, isLoading, isError, status } = useLiveQuery((q) =>
136 q.from({ todos: todoCollection })
138​
139if (isLoading) return <div>Loading...</div>
140if (isError) return <div>Error: {status}</div>
141​
142return (
143 <ul>
144 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
145 </ul>
147```
148​
149## Call Signature
150​
151```ts
152function useLiveQuery<TContext>(config, deps?): object
153```
154​
155Defined in: [useLiveQuery.ts:113](https://github.com/TanStack/db/blob/main/packages/react-db/src/useLiveQuery.ts#L113)
156​
157Create a live query using configuration object
158​
159### Type Parameters
160​
161• **TContext** *extends* `Context`
162​
163### Parameters
164​
165#### config
166​
167`LiveQueryCollectionConfig`\<`TContext`\>
168​
169Configuration object with query and options
170​
171#### deps?
172​
173`unknown`[]
174​
175Array of dependencies that trigger query re-execution when changed
176​
177### Returns
178​
179`object`
180​
181Object with reactive data, state, and status information
182​
183#### collection
184​
185```ts
186collection: Collection<{ [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }, string | number, {}>;
187```
188​
189#### data
190​
191```ts
192data: { [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }[];
193```
194​
195#### isCleanedUp
196​
197```ts
198isCleanedUp: boolean;
199```
200​
201#### isError
202​
203```ts
204isError: boolean;
205```
206​
207#### isIdle
208​
209```ts
210isIdle: boolean;
211```
212​
213#### isLoading
214​
215```ts
216isLoading: boolean;
217```
218​
219#### isReady
220​
221```ts
222isReady: boolean;
223```
224​
225#### state
226​
227```ts
228state: Map<string | number, { [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }>;
229```
230​
231#### status
232​
233```ts
234status: CollectionStatus;
235```
236​
237### Examples
238​
239```ts
240// Basic config object usage
241const { data, status } = useLiveQuery({
242 query: (q) => q.from({ todos: todosCollection }),
243 gcTime: 60000
244})
245```
246​
247```ts
248// With query builder and options
249const queryBuilder = new Query()
250 .from({ persons: collection })
251 .where(({ persons }) => gt(persons.age, 30))
252 .select(({ persons }) => ({ id: persons.id, name: persons.name }))
253​
254const { data, isReady } = useLiveQuery({ query: queryBuilder })
255```
256​
257```ts
258// Handle all states uniformly
259const { data, isLoading, isReady, isError } = useLiveQuery({
260 query: (q) => q.from({ items: itemCollection })
261})
262​
263if (isLoading) return <div>Loading...</div>
264if (isError) return <div>Something went wrong</div>
265if (!isReady) return <div>Preparing...</div>
266​
267return <div>{data.length} items loaded</div>
268```
269​
270## Call Signature
271​
272```ts
273function useLiveQuery<TResult, TKey, TUtils>(liveQueryCollection): object
274```
275​
276Defined in: [useLiveQuery.ts:158](https://github.com/TanStack/db/blob/main/packages/react-db/src/useLiveQuery.ts#L158)
277​
278Subscribe to an existing live query collection
279​
280### Type Parameters
281​
282• **TResult** *extends* `object`
283​
284• **TKey** *extends* `string` \| `number`
285​
286• **TUtils** *extends* `Record`\<`string`, `any`\>
287​
288### Parameters
289​
290#### liveQueryCollection
291​
292`Collection`\<`TResult`, `TKey`, `TUtils`\>
293​
294Pre-created live query collection to subscribe to
295​
296### Returns
297​
298`object`
299​
300Object with reactive data, state, and status information
301​
302#### collection
303​
304```ts
305collection: Collection<TResult, TKey, TUtils>;
306```
307​
308#### data
309​
310```ts
311data: TResult[];
312```
313​
314#### isCleanedUp
315​
316```ts
317isCleanedUp: boolean;
318```
319​
320#### isError
321​
322```ts
323isError: boolean;
324```
325​
326#### isIdle
327​
328```ts
329isIdle: boolean;
330```
331​
332#### isLoading
333​
334```ts
335isLoading: boolean;
336```
337​
338#### isReady
339​
340```ts
341isReady: boolean;
342```
343​
344#### state
345​
346```ts
347state: Map<TKey, TResult>;
348```
349​
350#### status
351​
352```ts
353status: CollectionStatus;
354```
355​
356### Examples
357​
358```ts
359// Using pre-created live query collection
360const myLiveQuery = createLiveQueryCollection((q) =>
361 q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
363const { data, collection } = useLiveQuery(myLiveQuery)
364```
365​
366```ts
367// Access collection methods directly
368const { data, collection, isReady } = useLiveQuery(existingCollection)
369​
370// Use collection for mutations
371const handleToggle = (id) => {
372 collection.update(id, draft => { draft.completed = !draft.completed })
374```
375​
376```ts
377// Handle states consistently
378const { data, isLoading, isError } = useLiveQuery(sharedCollection)
379​
380if (isLoading) return <div>Loading...</div>
381if (isError) return <div>Error loading data</div>
382​
383return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
384```