@tanstack/react-db
Version:
React integration for @tanstack/db
58 lines (57 loc) • 2.01 kB
JavaScript
import { useOptionalDbClient } from "./DbProvider.js";
import { getPreparedSources } from "./source-id-bindings.js";
import { useEffect, useRef } from "react";
import { createEffect, prepareLiveQueryValue } from "@tanstack/db";
// src/useLiveQueryEffect.ts
/**
* React hook for creating a reactive effect that fires handlers when rows
* enter, exit, or update within a query result.
*
* The effect is created on mount and disposed on unmount. If `deps` change,
* the previous effect is disposed and a new one is created.
*
* @example
* ```tsx
* function ChatComponent() {
* useLiveQueryEffect(
* {
* query: (q) => q.from({ msg: messages }).where(({ msg }) => eq(msg.role, 'user')),
* skipInitial: true,
* onEnter: async (event) => {
* await generateResponse(event.value)
* },
* },
* []
* )
*
* return <div>...</div>
* }
* ```
*/
function useLiveQueryEffect(config, deps = []) {
const client = useOptionalDbClient();
const configRef = useRef(config);
configRef.current = config;
useEffect(() => {
const query = prepareLiveQueryValue(config.query, client);
if (!client) getPreparedSources(query, client, `useLiveQueryEffect`);
const effect = createEffect({
id: config.id,
query,
skipInitial: config.skipInitial,
onEnter: (event, ctx) => configRef.current.onEnter?.(event, ctx),
onUpdate: (event, ctx) => configRef.current.onUpdate?.(event, ctx),
onExit: (event, ctx) => configRef.current.onExit?.(event, ctx),
onBatch: (events, ctx) => configRef.current.onBatch?.(events, ctx),
onError: config.onError ? (error, event) => configRef.current.onError?.(error, event) : void 0,
onSourceError: config.onSourceError ? (error) => configRef.current.onSourceError?.(error) : void 0
});
return () => {
effect.dispose().catch((error) => {
console.error(`[useLiveQueryEffect] failed to dispose effect:`, error);
});
};
}, [...deps, client]);
}
export { useLiveQueryEffect };
//# sourceMappingURL=useLiveQueryEffect.js.map