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

useLiveQuery.md

347 lines8.1 KB

1---
2id: useLiveQuery
3title: useLiveQuery
4---
5​
6# Function: useLiveQuery()
7​
8## Call Signature
9​
10```ts
11function useLiveQuery<TContext>(queryFn): Accessor<{ [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }[]> & object;
12```
13​
14Defined in: [useLiveQuery.ts:98](https://github.com/TanStack/db/blob/main/packages/solid-db/src/useLiveQuery.ts#L98)
15​
16Create a live query using a query function
17​
18### Type Parameters
19​
20#### TContext
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### Returns
33​
34Accessor that returns data with Suspense support, with state and status information as properties
35​
36### Examples
37​
38```ts
39// Basic query with object syntax
40const todosQuery = useLiveQuery((q) =>
41 q.from({ todos: todosCollection })
42 .where(({ todos }) => eq(todos.completed, false))
43 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
45```
46​
47```ts
48// With dependencies that trigger re-execution
49const todosQuery = useLiveQuery(
50 (q) => q.from({ todos: todosCollection })
51 .where(({ todos }) => gt(todos.priority, minPriority())),
53```
54​
55```ts
56// Join pattern
57const personIssues = useLiveQuery((q) =>
58 q.from({ issues: issueCollection })
59 .join({ persons: personCollection }, ({ issues, persons }) =>
60 eq(issues.userId, persons.id)
61 )
62 .select(({ issues, persons }) => ({
63 id: issues.id,
64 title: issues.title,
65 userName: persons.name
66 }))
68```
69​
70```ts
71// Handle loading and error states
72const todosQuery = useLiveQuery((q) =>
73 q.from({ todos: todoCollection })
75​
76return (
77 <Switch>
78 <Match when={todosQuery.isLoading}>
79 <div>Loading...</div>
80 </Match>
81 <Match when={todosQuery.isError}>
82 <div>Error: {todosQuery.status}</div>
83 </Match>
84 <Match when={todosQuery.isReady}>
85 <For each={todosQuery()}>
86 {(todo) => <li key={todo.id}>{todo.text}</li>}
87 </For>
88 </Match>
89 </Switch>
91```
92​
93```ts
94// Use Suspense boundaries
95const todosQuery = useLiveQuery((q) =>
96 q.from({ todos: todoCollection })
98​
99return (
100 <Suspense fallback={<div>Loading...</div>}>
101 <For each={todosQuery()}>
102 {(todo) => <li key={todo.id}>{todo.text}</li>}
103 </For>
104 </Suspense>
106```
107​
108## Call Signature
109​
110```ts
111function useLiveQuery<TContext>(queryFn): Accessor<{ [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }[]> & object;
112```
113​
114Defined in: [useLiveQuery.ts:117](https://github.com/TanStack/db/blob/main/packages/solid-db/src/useLiveQuery.ts#L117)
115​
116Create a live query using a query function
117​
118### Type Parameters
119​
120#### TContext
121​
122`TContext` *extends* `Context`
123​
124### Parameters
125​
126#### queryFn
127​
128(`q`) => `QueryBuilder`\<`TContext`\> \| `null` \| `undefined`
129​
130Query function that defines what data to fetch
131​
132### Returns
133​
134Accessor that returns data with Suspense support, with state and status information as properties
135​
136### Examples
137​
138```ts
139// Basic query with object syntax
140const todosQuery = useLiveQuery((q) =>
141 q.from({ todos: todosCollection })
142 .where(({ todos }) => eq(todos.completed, false))
143 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
145```
146​
147```ts
148// With dependencies that trigger re-execution
149const todosQuery = useLiveQuery(
150 (q) => q.from({ todos: todosCollection })
151 .where(({ todos }) => gt(todos.priority, minPriority())),
153```
154​
155```ts
156// Join pattern
157const personIssues = useLiveQuery((q) =>
158 q.from({ issues: issueCollection })
159 .join({ persons: personCollection }, ({ issues, persons }) =>
160 eq(issues.userId, persons.id)
161 )
162 .select(({ issues, persons }) => ({
163 id: issues.id,
164 title: issues.title,
165 userName: persons.name
166 }))
168```
169​
170```ts
171// Handle loading and error states
172const todosQuery = useLiveQuery((q) =>
173 q.from({ todos: todoCollection })
175​
176return (
177 <Switch>
178 <Match when={todosQuery.isLoading}>
179 <div>Loading...</div>
180 </Match>
181 <Match when={todosQuery.isError}>
182 <div>Error: {todosQuery.status}</div>
183 </Match>
184 <Match when={todosQuery.isReady}>
185 <For each={todosQuery()}>
186 {(todo) => <li key={todo.id}>{todo.text}</li>}
187 </For>
188 </Match>
189 </Switch>
191```
192​
193```ts
194// Use Suspense boundaries
195const todosQuery = useLiveQuery((q) =>
196 q.from({ todos: todoCollection })
198​
199return (
200 <Suspense fallback={<div>Loading...</div>}>
201 <For each={todosQuery()}>
202 {(todo) => <li key={todo.id}>{todo.text}</li>}
203 </For>
204 </Suspense>
206```
207​
208## Call Signature
209​
210```ts
211function useLiveQuery<TContext>(config): Accessor<{ [K in string | number | symbol]: (TContext["result"] extends object ? any[any] : TContext["hasJoins"] extends true ? TContext["schema"] : TContext["schema"][TContext["fromSourceName"]])[K] }[]> & object;
212```
213​
214Defined in: [useLiveQuery.ts:178](https://github.com/TanStack/db/blob/main/packages/solid-db/src/useLiveQuery.ts#L178)
215​
216Create a live query using configuration object
217​
218### Type Parameters
219​
220#### TContext
221​
222`TContext` *extends* `Context`
223​
224### Parameters
225​
226#### config
227​
228`Accessor`\<`LiveQueryCollectionConfig`\<`TContext`, \{ \[K in string \| number \| symbol\]: (TContext\["result"\] extends object ? any\[any\] : TContext\["hasJoins"\] extends true ? TContext\["schema"\] : TContext\["schema"\]\[TContext\["fromSourceName"\]\])\[K\] \} & `object`\>\>
229​
230Configuration object with query and options
231​
232### Returns
233​
234Accessor that returns data with Suspense support, with state and status information as properties
235​
236### Examples
237​
238```ts
239// Basic config object usage
240const todosQuery = useLiveQuery(() => ({
241 query: (q) => q.from({ todos: todosCollection }),
242 gcTime: 60000
243}))
244```
245​
246```ts
247// With query builder and options
248const queryBuilder = new Query()
249 .from({ persons: collection })
250 .where(({ persons }) => gt(persons.age, 30))
251 .select(({ persons }) => ({ id: persons.id, name: persons.name }))
252​
253const personsQuery = useLiveQuery(() => ({ query: queryBuilder }))
254```
255​
256```ts
257// Handle all states uniformly
258const itemsQuery = useLiveQuery(() => ({
259 query: (q) => q.from({ items: itemCollection })
260}))
261​
262return (
263 <Switch fallback={<div>{itemsQuery().length} items loaded</div>}>
264 <Match when={itemsQuery.isLoading}>
265 <div>Loading...</div>
266 </Match>
267 <Match when={itemsQuery.isError}>
268 <div>Something went wrong</div>
269 </Match>
270 <Match when={!itemsQuery.isReady}>
271 <div>Preparing...</div>
272 </Match>
273 </Switch>
275```
276​
277## Call Signature
278​
279```ts
280function useLiveQuery<TResult, TKey, TUtils>(liveQueryCollection): Accessor<TResult[]> & object;
281```
282​
283Defined in: [useLiveQuery.ts:232](https://github.com/TanStack/db/blob/main/packages/solid-db/src/useLiveQuery.ts#L232)
284​
285Subscribe to an existing live query collection
286​
287### Type Parameters
288​
289#### TResult
290​
291`TResult` *extends* `object`
292​
293#### TKey
294​
295`TKey` *extends* `string` \| `number`
296​
297#### TUtils
298​
299`TUtils` *extends* `Record`\<`string`, `any`\>
300​
301### Parameters
302​
303#### liveQueryCollection
304​
305`Accessor`\<`Collection`\<`TResult`, `TKey`, `TUtils`, `StandardSchemaV1`\<`unknown`, `unknown`\>, `TResult`\>\>
306​
307Pre-created live query collection to subscribe to
308​
309### Returns
310​
311Accessor that returns data with Suspense support, with state and status information as properties
312​
313### Examples
314​
315```ts
316// Using pre-created live query collection
317const myLiveQuery = createLiveQueryCollection((q) =>
318 q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
320const todosQuery = useLiveQuery(() => myLiveQuery)
321```
322​
323```ts
324// Access collection methods directly
325const existingQuery = useLiveQuery(() => existingCollection)
326​
327// Use collection for mutations
328const handleToggle = (id) => {
329 existingQuery.collection.update(id, draft => { draft.completed = !draft.completed })
331```
332​
333```ts
334// Handle states consistently
335const sharedQuery = useLiveQuery(() => sharedCollection)
336​
337return (
338 <Switch fallback={<div><For each={sharedQuery()}>{(item) => <Item key={item.id} {...item} />}</For></div>}>
339 <Match when={sharedQuery.isLoading}>
340 <div>Loading...</div>
341 </Match>
342 <Match when={sharedQuery.isError}>
343 <div>Error loading data</div>
344 </Match>
345 </Switch>
347```