Open History to see the last commit
1import { useEffect, useRef } from 'react'
2import { createEffect, prepareLiveQueryValue } from '@tanstack/db'
3import { useOptionalDbClient } from './DbProvider'
4import { getPreparedSources } from './source-id-bindings'
5import type { EffectConfig } from '@tanstack/db'
6
7/**
8 * React hook for creating a reactive effect that fires handlers when rows
9 * enter, exit, or update within a query result.
10 *
11 * The effect is created on mount and disposed on unmount. If `deps` change,
12 * the previous effect is disposed and a new one is created.
13 *
14 * @example
15 * ```tsx
16 * function ChatComponent() {
17 * useLiveQueryEffect(
18 * {
19 * query: (q) => q.from({ msg: messages }).where(({ msg }) => eq(msg.role, 'user')),
20 * skipInitial: true,
21 * onEnter: async (event) => {
22 * await generateResponse(event.value)
23 * },
24 * },
25 * []
26 * )
27 *
28 * return <div>...</div>
29 * }
30 * ```
31 */
32export function useLiveQueryEffect<
33 TRow extends object = Record<string, unknown>,
34 TKey extends string | number = string | number,
35>(config: EffectConfig<TRow, TKey>, deps: React.DependencyList = []): void {
36 const client = useOptionalDbClient()
37 const configRef = useRef<EffectConfig<TRow, TKey>>(config)
38 configRef.current = config
39
40 useEffect(() => {
41 const query = prepareLiveQueryValue(config.query, client)
42 if (!client) getPreparedSources(query, client, `useLiveQueryEffect`)
43 const effect = createEffect<TRow, TKey>({
44 id: config.id,
45 query: query as EffectConfig<TRow, TKey>[`query`],
46 skipInitial: config.skipInitial,
47 onEnter: (event, ctx) => configRef.current.onEnter?.(event, ctx),
48 onUpdate: (event, ctx) => configRef.current.onUpdate?.(event, ctx),
49 onExit: (event, ctx) => configRef.current.onExit?.(event, ctx),
50 onBatch: (events, ctx) => configRef.current.onBatch?.(events, ctx),
51 onError: config.onError
52 ? (error, event) => configRef.current.onError?.(error, event)
53 : undefined,
54 onSourceError: config.onSourceError
55 ? (error) => configRef.current.onSourceError?.(error)
56 : undefined,
57 })
58
59 return () => {
60 // React cannot await cleanup. Report a failed source release.
61 void effect.dispose().catch((error) => {
62 console.error(`[useLiveQueryEffect] failed to dispose effect:`, error)
63 })
64 }
65 }, [...deps, client])
66}