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