Open History to see the last commit
1import {
2 computed,
3 getCurrentInstance,
4 nextTick,
5 onUnmounted,
6 reactive,
7 ref,
8 toValue,
9 watchEffect,
10} from "vue"
11import { createLiveQueryCollection } from "@tanstack/db"
12import type {
13 ChangeMessage,
14 Collection,
15 CollectionStatus,
16 Context,
17 GetResult,
18 InitialQueryBuilder,
19 LiveQueryCollectionConfig,
20 QueryBuilder,
21} from "@tanstack/db"
22import type { ComputedRef, MaybeRefOrGetter } from "vue"
23
24/**
25 * Return type for useLiveQuery hook
26 * @property state - Reactive Map of query results (key → item)
27 * @property data - Reactive array of query results in order
28 * @property collection - The underlying query collection instance
29 * @property status - Current query status
30 * @property isLoading - True while initial query data is loading
31 * @property isReady - True when query has received first data and is ready
32 * @property isIdle - True when query hasn't started yet
33 * @property isError - True when query encountered an error
34 * @property isCleanedUp - True when query has been cleaned up
35 */
36export interface UseLiveQueryReturn<T extends object> {
37 state: ComputedRef<Map<string | number, T>>
38 data: ComputedRef<Array<T>>
39 collection: ComputedRef<Collection<T, string | number, {}>>
40 status: ComputedRef<CollectionStatus>
41 isLoading: ComputedRef<boolean>
42 isReady: ComputedRef<boolean>
43 isIdle: ComputedRef<boolean>
44 isError: ComputedRef<boolean>
45 isCleanedUp: ComputedRef<boolean>
46}
47
48export interface UseLiveQueryReturnWithCollection<
49 T extends object,
50 TKey extends string | number,
51 TUtils extends Record<string, any>,
52> {
53 state: ComputedRef<Map<TKey, T>>
54 data: ComputedRef<Array<T>>
55 collection: ComputedRef<Collection<T, TKey, TUtils>>
56 status: ComputedRef<CollectionStatus>
57 isLoading: ComputedRef<boolean>
58 isReady: ComputedRef<boolean>
59 isIdle: ComputedRef<boolean>
60 isError: ComputedRef<boolean>
61 isCleanedUp: ComputedRef<boolean>
62}
63
64/**
65 * Create a live query using a query function
66 * @param queryFn - Query function that defines what data to fetch
67 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
68 * @returns Reactive object with query data, state, and status information
69 * @example
70 * // Basic query with object syntax
71 * const { data, isLoading } = useLiveQuery((q) =>
72 * q.from({ todos: todosCollection })
73 * .where(({ todos }) => eq(todos.completed, false))
74 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
75 * )
76 *
77 * @example
78 * // With reactive dependencies
79 * const minPriority = ref(5)
80 * const { data, state } = useLiveQuery(
81 * (q) => q.from({ todos: todosCollection })
82 * .where(({ todos }) => gt(todos.priority, minPriority.value)),
83 * [minPriority] // Re-run when minPriority changes
84 * )
85 *
86 * @example
87 * // Join pattern
88 * const { data } = useLiveQuery((q) =>
89 * q.from({ issues: issueCollection })
90 * .join({ persons: personCollection }, ({ issues, persons }) =>
91 * eq(issues.userId, persons.id)
92 * )
93 * .select(({ issues, persons }) => ({
94 * id: issues.id,
95 * title: issues.title,
96 * userName: persons.name
97 * }))
98 * )
99 *
100 * @example
101 * // Handle loading and error states in template
102 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
103 * q.from({ todos: todoCollection })
104 * )
105 *
106 * // In template:
107 * // <div v-if="isLoading">Loading...</div>
108 * // <div v-else-if="isError">Error: {{ status }}</div>
109 * // <ul v-else>
110 * // <li v-for="todo in data" :key="todo.id">{{ todo.text }}</li>
111 * // </ul>
112 */
113// Overload 1: Accept just the query function
114export function useLiveQuery<TContext extends Context>(
115 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
116 deps?: Array<MaybeRefOrGetter<unknown>>
117): UseLiveQueryReturn<GetResult<TContext>>
118
119/**
120 * Create a live query using configuration object
121 * @param config - Configuration object with query and options
122 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
123 * @returns Reactive object with query data, state, and status information
124 * @example
125 * // Basic config object usage
126 * const { data, status } = useLiveQuery({
127 * query: (q) => q.from({ todos: todosCollection }),
128 * gcTime: 60000
129 * })
130 *
131 * @example
132 * // With reactive dependencies
133 * const filter = ref('active')
134 * const { data, isReady } = useLiveQuery({
135 * query: (q) => q.from({ todos: todosCollection })
136 * .where(({ todos }) => eq(todos.status, filter.value))
137 * }, [filter])
138 *
139 * @example
140 * // Handle all states uniformly
141 * const { data, isLoading, isReady, isError } = useLiveQuery({
142 * query: (q) => q.from({ items: itemCollection })
143 * })
144 *
145 * // In template:
146 * // <div v-if="isLoading">Loading...</div>
147 * // <div v-else-if="isError">Something went wrong</div>
148 * // <div v-else-if="!isReady">Preparing...</div>
149 * // <div v-else>{{ data.length }} items loaded</div>
150 */
151// Overload 2: Accept config object
152export function useLiveQuery<TContext extends Context>(
153 config: LiveQueryCollectionConfig<TContext>,
154 deps?: Array<MaybeRefOrGetter<unknown>>
155): UseLiveQueryReturn<GetResult<TContext>>
156
157/**
158 * Subscribe to an existing query collection (can be reactive)
159 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)
160 * @returns Reactive object with query data, state, and status information
161 * @example
162 * // Using pre-created query collection
163 * const myLiveQuery = createLiveQueryCollection((q) =>
164 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
165 * )
166 * const { data, collection } = useLiveQuery(myLiveQuery)
167 *
168 * @example
169 * // Reactive query collection reference
170 * const selectedQuery = ref(todosQuery)
171 * const { data, collection } = useLiveQuery(selectedQuery)
172 *
173 * // Switch queries reactively
174 * selectedQuery.value = archiveQuery
175 *
176 * @example
177 * // Access query collection methods directly
178 * const { data, collection, isReady } = useLiveQuery(existingQuery)
179 *
180 * // Use underlying collection for mutations
181 * const handleToggle = (id) => {
182 * collection.value.update(id, draft => { draft.completed = !draft.completed })
183 * }
184 *
185 * @example
186 * // Handle states consistently
187 * const { data, isLoading, isError } = useLiveQuery(sharedQuery)
188 *
189 * // In template:
190 * // <div v-if="isLoading">Loading...</div>
191 * // <div v-else-if="isError">Error loading data</div>
192 * // <div v-else>
193 * // <Item v-for="item in data" :key="item.id" v-bind="item" />
194 * // </div>
195 */
196// Overload 3: Accept pre-created live query collection (can be reactive)
197export function useLiveQuery<
198 TResult extends object,
199 TKey extends string | number,
200 TUtils extends Record<string, any>,
201>(
202 liveQueryCollection: MaybeRefOrGetter<Collection<TResult, TKey, TUtils>>
203): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>
204
205// Implementation
206export function useLiveQuery(
207 configOrQueryOrCollection: any,
208 deps: Array<MaybeRefOrGetter<unknown>> = []
209): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
210 const collection = computed(() => {
211 // First check if the original parameter might be a ref/getter
212 // by seeing if toValue returns something different than the original
213 let unwrappedParam = configOrQueryOrCollection
214 try {
215 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
216 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
217 unwrappedParam = potentiallyUnwrapped
218 }
219 } catch {
220 // If toValue fails, use original parameter
221 unwrappedParam = configOrQueryOrCollection
222 }
223
224 // Check if it's already a collection by checking for specific collection methods
225 const isCollection =
226 unwrappedParam &&
227 typeof unwrappedParam === `object` &&
228 typeof unwrappedParam.subscribeChanges === `function` &&
229 typeof unwrappedParam.startSyncImmediate === `function` &&
230 typeof unwrappedParam.id === `string`
231
232 if (isCollection) {
233 // It's already a collection, ensure sync is started for Vue hooks
234 // Only start sync if the collection is in idle state
235 if (unwrappedParam.status === `idle`) {
236 unwrappedParam.startSyncImmediate()
237 }
238 return unwrappedParam
239 }
240
241 // Reference deps to make computed reactive to them
242 deps.forEach((dep) => toValue(dep))
243
244 // Ensure we always start sync for Vue hooks
245 if (typeof unwrappedParam === `function`) {
246 return createLiveQueryCollection({
247 query: unwrappedParam,
248 startSync: true,
249 })
250 } else {
251 return createLiveQueryCollection({
252 ...unwrappedParam,
253 startSync: true,
254 })
255 }
256 })
257
258 // Reactive state that gets updated granularly through change events
259 const state = reactive(new Map<string | number, any>())
260
261 // Reactive data array that maintains sorted order
262 const internalData = reactive<Array<any>>([])
263
264 // Computed wrapper for the data to match expected return type
265 const data = computed(() => internalData)
266
267 // Track collection status reactively
268 const status = ref(collection.value.status)
269
270 // Helper to sync data array from collection in correct order
271 const syncDataFromCollection = (
272 currentCollection: Collection<any, any, any>
273 ) => {
274 internalData.length = 0
275 internalData.push(...Array.from(currentCollection.values()))
276 }
277
278 // Track current unsubscribe function
279 let currentUnsubscribe: (() => void) | null = null
280
281 // Watch for collection changes and subscribe to updates
282 watchEffect((onInvalidate) => {
283 const currentCollection = collection.value
284
285 // Update status ref whenever the effect runs
286 status.value = currentCollection.status
287
288 // Clean up previous subscription
289 if (currentUnsubscribe) {
290 currentUnsubscribe()
291 }
292
293 // Initialize state with current collection data
294 state.clear()
295 for (const [key, value] of currentCollection.entries()) {
296 state.set(key, value)
297 }
298
299 // Initialize data array in correct order
300 syncDataFromCollection(currentCollection)
301
302 // Listen for the first ready event to catch status transitions
303 // that might not trigger change events (fixes async status transition bug)
304 currentCollection.onFirstReady(() => {
305 // Use nextTick to ensure Vue reactivity updates properly
306 nextTick(() => {
307 status.value = currentCollection.status
308 })
309 })
310
311 // Subscribe to collection changes with granular updates
312 const subscription = currentCollection.subscribeChanges(
313 (changes: Array<ChangeMessage<any>>) => {
314 // Apply each change individually to the reactive state
315 for (const change of changes) {
316 switch (change.type) {
317 case `insert`:
318 case `update`:
319 state.set(change.key, change.value)
320 break
321 case `delete`:
322 state.delete(change.key)
323 break
324 }
325 }
326
327 // Update the data array to maintain sorted order
328 syncDataFromCollection(currentCollection)
329 // Update status ref on every change
330 status.value = currentCollection.status
331 },
332 {
333 includeInitialState: true,
334 }
335 )
336
337 currentUnsubscribe = subscription.unsubscribe.bind(subscription)
338
339 // Preload collection data if not already started
340 if (currentCollection.status === `idle`) {
341 currentCollection.preload().catch(console.error)
342 }
343
344 // Cleanup when effect is invalidated
345 onInvalidate(() => {
346 if (currentUnsubscribe) {
347 currentUnsubscribe()
348 currentUnsubscribe = null
349 }
350 })
351 })
352
353 // Cleanup on unmount (only if we're in a component context)
354 const instance = getCurrentInstance()
355 if (instance) {
356 onUnmounted(() => {
357 if (currentUnsubscribe) {
358 currentUnsubscribe()
359 }
360 })
361 }
362
363 return {
364 state: computed(() => state),
365 data,
366 collection: computed(() => collection.value),
367 status: computed(() => status.value),
368 isLoading: computed(
369 () => status.value === `loading` || status.value === `initialCommit`
370 ),
371 isReady: computed(() => status.value === `ready`),
372 isIdle: computed(() => status.value === `idle`),
373 isError: computed(() => status.value === `error`),
374 isCleanedUp: computed(() => status.value === `cleaned-up`),
375 }
376}