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

useLiveQuery.ts

328 lines9.5 KB

1import {
2 batch,
3 createComputed,
4 createMemo,
5 createResource,
6 createSignal,
7 onCleanup,
8} from "solid-js"
9import { ReactiveMap } from "@solid-primitives/map"
10import { CollectionImpl, createLiveQueryCollection } from "@tanstack/db"
11import { createStore, reconcile } from "solid-js/store"
12import type { Accessor } from "solid-js"
13import type {
14 ChangeMessage,
15 Collection,
16 CollectionStatus,
17 Context,
18 GetResult,
19 InitialQueryBuilder,
20 LiveQueryCollectionConfig,
21 QueryBuilder,
22} from "@tanstack/db"
23​
24/**
25 * Create a live query using a query function
26 * @param queryFn - Query function that defines what data to fetch
27 * @returns Object with reactive data, state, and status information
28 * @example
29 * // Basic query with object syntax
30 * const todosQuery = useLiveQuery((q) =>
31 * q.from({ todos: todosCollection })
32 * .where(({ todos }) => eq(todos.completed, false))
33 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
34 * )
35 *
36 * @example
37 * // With dependencies that trigger re-execution
38 * const todosQuery = useLiveQuery(
39 * (q) => q.from({ todos: todosCollection })
40 * .where(({ todos }) => gt(todos.priority, minPriority())),
41 * )
42 *
43 * @example
44 * // Join pattern
45 * const personIssues = useLiveQuery((q) =>
46 * q.from({ issues: issueCollection })
47 * .join({ persons: personCollection }, ({ issues, persons }) =>
48 * eq(issues.userId, persons.id)
49 * )
50 * .select(({ issues, persons }) => ({
51 * id: issues.id,
52 * title: issues.title,
53 * userName: persons.name
54 * }))
55 * )
56 *
57 * @example
58 * // Handle loading and error states
59 * const todosQuery = useLiveQuery((q) =>
60 * q.from({ todos: todoCollection })
61 * )
62 *
63 * return (
64 * <Switch>
65 * <Match when={todosQuery.isLoading()}>
66 * <div>Loading...</div>
67 * </Match>
68 * <Match when={todosQuery.isError()}>
69 * <div>Error: {todosQuery.status()}</div>
70 * </Match>
71 * <Match when={todosQuery.isReady()}>
72 * <For each={todosQuery.data()}>
73 * {(todo) => <li key={todo.id}>{todo.text}</li>}
74 * </For>
75 * </Match>
76 * </Switch>
77 * )
78 */
79// Overload 1: Accept just the query function
80export function useLiveQuery<TContext extends Context>(
81 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>
82): {
83 state: ReactiveMap<string | number, GetResult<TContext>>
84 data: Array<GetResult<TContext>>
85 collection: Accessor<Collection<GetResult<TContext>, string | number, {}>>
86 status: Accessor<CollectionStatus>
87 isLoading: Accessor<boolean>
88 isReady: Accessor<boolean>
89 isIdle: Accessor<boolean>
90 isError: Accessor<boolean>
91 isCleanedUp: Accessor<boolean>
93​
94/**
95 * Create a live query using configuration object
96 * @param config - Configuration object with query and options
97 * @returns Object with reactive data, state, and status information
98 * @example
99 * // Basic config object usage
100 * const todosQuery = useLiveQuery(() => ({
101 * query: (q) => q.from({ todos: todosCollection }),
102 * gcTime: 60000
103 * }))
104 *
105 * @example
106 * // With query builder and options
107 * const queryBuilder = new Query()
108 * .from({ persons: collection })
109 * .where(({ persons }) => gt(persons.age, 30))
110 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
111 *
112 * const personsQuery = useLiveQuery(() => ({ query: queryBuilder }))
113 *
114 * @example
115 * // Handle all states uniformly
116 * const itemsQuery = useLiveQuery(() => ({
117 * query: (q) => q.from({ items: itemCollection })
118 * }))
119 *
120 * return (
121 * <Switch fallback={<div>{itemsQuery.data.length} items loaded</div>}>
122 * <Match when={itemsQuery.isLoading()}>
123 * <div>Loading...</div>
124 * </Match>
125 * <Match when={itemsQuery.isError()}>
126 * <div>Something went wrong</div>
127 * </Match>
128 * <Match when={!itemsQuery.isReady()}>
129 * <div>Preparing...</div>
130 * </Match>
131 * </Switch>
132 * )
133 */
134// Overload 2: Accept config object
135export function useLiveQuery<TContext extends Context>(
136 config: Accessor<LiveQueryCollectionConfig<TContext>>
137): {
138 state: ReactiveMap<string | number, GetResult<TContext>>
139 data: Array<GetResult<TContext>>
140 collection: Accessor<Collection<GetResult<TContext>, string | number, {}>>
141 status: Accessor<CollectionStatus>
142 isLoading: Accessor<boolean>
143 isReady: Accessor<boolean>
144 isIdle: Accessor<boolean>
145 isError: Accessor<boolean>
146 isCleanedUp: Accessor<boolean>
148​
149/**
150 * Subscribe to an existing live query collection
151 * @param liveQueryCollection - Pre-created live query collection to subscribe to
152 * @returns Object with reactive data, state, and status information
153 * @example
154 * // Using pre-created live query collection
155 * const myLiveQuery = createLiveQueryCollection((q) =>
156 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
157 * )
158 * const todosQuery = useLiveQuery(() => myLiveQuery)
159 *
160 * @example
161 * // Access collection methods directly
162 * const existingQuery = useLiveQuery(() => existingCollection)
163 *
164 * // Use collection for mutations
165 * const handleToggle = (id) => {
166 * existingQuery.collection().update(id, draft => { draft.completed = !draft.completed })
167 * }
168 *
169 * @example
170 * // Handle states consistently
171 * const sharedQuery = useLiveQuery(() => sharedCollection)
172 *
173 * return (
174 * <Switch fallback={<div><For each={sharedQuery.data()}>{(item) => <Item key={item.id} {...item} />}</For></div>}>
175 * <Match when={sharedQuery.isLoading()}>
176 * <div>Loading...</div>
177 * </Match>
178 * <Match when={sharedQuery.isError()}>
179 * <div>Error loading data</div>
180 * </Match>
181 * </Switch>
182 * )
183 */
184// Overload 3: Accept pre-created live query collection
185export function useLiveQuery<
186 TResult extends object,
187 TKey extends string | number,
188 TUtils extends Record<string, any>,
189>(
190 liveQueryCollection: Accessor<Collection<TResult, TKey, TUtils>>
191): {
192 state: ReactiveMap<TKey, TResult>
193 data: Array<TResult>
194 collection: Accessor<Collection<TResult, TKey, TUtils>>
195 status: Accessor<CollectionStatus>
196 isLoading: Accessor<boolean>
197 isReady: Accessor<boolean>
198 isIdle: Accessor<boolean>
199 isError: Accessor<boolean>
200 isCleanedUp: Accessor<boolean>
202​
203// Implementation - use function overloads to infer the actual collection type
204export function useLiveQuery(
205 configOrQueryOrCollection: (queryFn?: any) => any
206) {
207 const collection = createMemo(
208 () => {
209 if (configOrQueryOrCollection.length === 1) {
210 return createLiveQueryCollection({
211 query: configOrQueryOrCollection,
212 startSync: true,
213 })
214 }
215​
216 const innerCollection = configOrQueryOrCollection()
217 if (innerCollection instanceof CollectionImpl) {
218 innerCollection.startSyncImmediate()
219 return innerCollection as Collection
220 }
221​
222 return createLiveQueryCollection({
223 ...innerCollection,
224 startSync: true,
225 })
226 },
227 undefined,
228 { name: `TanstackDBCollectionMemo` }
229 )
230​
231 // Reactive state that gets updated granularly through change events
232 const state = new ReactiveMap<string | number, any>()
233​
234 // Reactive data array that maintains sorted order
235 const [data, setData] = createStore<Array<any>>([], {
236 name: `TanstackDBData`,
237 })
238​
239 // Track collection status reactively
240 const [status, setStatus] = createSignal(collection().status, {
241 name: `TanstackDBStatus`,
242 })
243​
244 // Helper to sync data array from collection in correct order
245 const syncDataFromCollection = (
246 currentCollection: Collection<any, any, any>
247 ) => {
248 setData((prev) =>
249 reconcile(Array.from(currentCollection.values()))(prev).filter(Boolean)
250 )
251 }
252​
253 // Track current unsubscribe function
254 let currentUnsubscribe: (() => void) | null = null
255​
256 createComputed(
257 () => {
258 const currentCollection = collection()
259​
260 // Update status ref whenever the effect runs
261 setStatus(currentCollection.status)
262​
263 // Initialize state with current collection data
264 state.clear()
265 for (const [key, value] of currentCollection.entries()) {
266 state.set(key, value)
267 }
268​
269 // Subscribe to collection changes with granular updates
270 const subscription = currentCollection.subscribeChanges(
271 (changes: Array<ChangeMessage<any>>) => {
272 // Apply each change individually to the reactive state
273 batch(() => {
274 for (const change of changes) {
275 switch (change.type) {
276 case `insert`:
277 case `update`:
278 state.set(change.key, change.value)
279 break
280 case `delete`:
281 state.delete(change.key)
282 break
283 }
284 }
285 })
286​
287 // Update the data array to maintain sorted order
288 syncDataFromCollection(currentCollection)
289​
290 // Update status ref on every change
291 setStatus(currentCollection.status)
292 },
293 {
294 includeInitialState: true,
295 }
296 )
297​
298 currentUnsubscribe = subscription.unsubscribe.bind(subscription)
299​
300 // Preload collection data if not already started
301 if (currentCollection.status === `idle`) {
302 createResource(() => currentCollection.preload())
303 }
304​
305 // Cleanup when computed is invalidated
306 onCleanup(() => {
307 if (currentUnsubscribe) {
308 currentUnsubscribe()
309 currentUnsubscribe = null
310 }
311 })
312 },
313 undefined,
314 { name: `TanstackDBSyncComputed` }
315 )
316​
317 return {
318 state,
319 data,
320 collection,
321 status,
322 isLoading: () => status() === `loading`,
323 isReady: () => status() === `ready`,
324 isIdle: () => status() === `idle`,
325 isError: () => status() === `error`,
326 isCleanedUp: () => status() === `cleaned-up`,
327 }