|
| 1 | +import { computed, toValue, watch } from "vue" |
| 2 | +import { useStore } from "@tanstack/vue-store" |
| 3 | +import { compileQuery, queryBuilder } from "@tanstack/db" |
| 4 | +import type { |
| 5 | + Collection, |
| 6 | + Context, |
| 7 | + InitialQueryBuilder, |
| 8 | + QueryBuilder, |
| 9 | + ResultsFromContext, |
| 10 | + Schema, |
| 11 | +} from "@tanstack/db" |
| 12 | +import type { ComputedRef, MaybeRefOrGetter } from "vue" |
| 13 | + |
| 14 | +export interface UseLiveQueryReturn<T extends object> { |
| 15 | + state: ComputedRef<Map<string, T>> |
| 16 | + data: ComputedRef<Array<T>> |
| 17 | + collection: ComputedRef<Collection<T>> |
| 18 | +} |
| 19 | + |
| 20 | +export function useLiveQuery< |
| 21 | + TResultContext extends Context<Schema> = Context<Schema>, |
| 22 | +>( |
| 23 | + queryFn: ( |
| 24 | + q: InitialQueryBuilder<Context<Schema>> |
| 25 | + ) => QueryBuilder<TResultContext>, |
| 26 | + deps: Array<MaybeRefOrGetter<unknown>> = [] |
| 27 | +): UseLiveQueryReturn<ResultsFromContext<TResultContext>> { |
| 28 | + const compiledQuery = computed(() => { |
| 29 | + // Just reference deps to make computed reactive to them |
| 30 | + deps.forEach((dep) => toValue(dep)) |
| 31 | + |
| 32 | + const query = queryFn(queryBuilder()) |
| 33 | + const compiled = compileQuery(query) |
| 34 | + compiled.start() |
| 35 | + return compiled |
| 36 | + }) |
| 37 | + |
| 38 | + const state = computed(() => { |
| 39 | + return useStore(compiledQuery.value.results.derivedState).value |
| 40 | + }) |
| 41 | + const data = computed(() => { |
| 42 | + return useStore(compiledQuery.value.results.derivedArray).value |
| 43 | + }) |
| 44 | + |
| 45 | + watch(compiledQuery, (newQuery, oldQuery, onInvalidate) => { |
| 46 | + if (newQuery.state === `stopped`) { |
| 47 | + newQuery.start() |
| 48 | + } |
| 49 | + |
| 50 | + onInvalidate(() => { |
| 51 | + oldQuery.stop() |
| 52 | + }) |
| 53 | + }) |
| 54 | + |
| 55 | + return { |
| 56 | + state, |
| 57 | + data, |
| 58 | + collection: computed(() => compiledQuery.value.results), |
| 59 | + } |
| 60 | +} |
0 commit comments