Using Queries
Use hypequery React hooks on a ClickHouse API: useQuery, useMutation, useDataset and useMetric, error handling, queries without input and common patterns.
Once you've set up @hypequery/react, you can use useQuery and useMutation in your components with full type safety.
useQuery
Fetch data from your hypequery API with automatic caching and refetching:
import { useQuery } from '@/lib/analytics'; function RevenueChart() { const { data, error, isLoading } = useQuery('weeklyRevenue', { startDate: '2025-01-01', }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return <div>Total: ${data.total}</div>; }
Type Safety
The query name and input are fully typed:
// ✅ Type-safe const { data } = useQuery('weeklyRevenue', { startDate: '2025-01-01', }); // ❌ TypeScript error - invalid query name const { data } = useQuery('invalidQuery', { ... }); // ❌ TypeScript error - invalid input const { data } = useQuery('weeklyRevenue', { invalidField: 'value', });
TanStack Query Options
All TanStack Query options are supported:
const { data } = useQuery('weeklyRevenue', { startDate: '2025-01-01' }, { staleTime: 5 * 60 * 1000, // 5 minutes refetchOnWindowFocus: false, enabled: isAuthenticated, // Conditional fetching } );
useMutation
Execute write operations or actions:
import { useMutation } from '@/lib/analytics'; function RebuildButton() { const rebuild = useMutation('rebuildMetrics'); return ( <button onClick={() => rebuild.mutate({ force: true })} disabled={rebuild.isPending} > {rebuild.isPending ? 'Rebuilding...' : 'Rebuild Metrics'} </button> ); }
Handling Success and Errors
const rebuild = useMutation('rebuildMetrics', { onSuccess: (data) => { console.log('Rebuild complete:', data); // Invalidate related queries queryClient.invalidateQueries({ queryKey: ['weeklyRevenue'] }); }, onError: (error) => { console.error('Rebuild failed:', error); }, });
Optimistic Updates
const updateMetric = useMutation('updateMetric', { onMutate: async (newData) => { // Cancel outgoing refetches await queryClient.cancelQueries({ queryKey: ['metrics'] }); // Snapshot current value const previous = queryClient.getQueryData(['metrics']); // Optimistically update queryClient.setQueryData(['metrics'], (old) => ({ ...old, ...newData, })); return { previous }; }, onError: (err, variables, context) => { // Rollback on error queryClient.setQueryData(['metrics'], context.previous); }, onSettled: () => { // Refetch after success or error queryClient.invalidateQueries({ queryKey: ['metrics'] }); }, });
useDataset
When you set up hooks with createAnalyticsHooks, use useDataset for semantic dataset endpoints. They take the same TanStack options as useQuery, and the input is the dataset query (dimensions, measures, filters, ordering, limits).
useDataset runs an ad hoc dataset query. Reference it by dataset name — the hook maps it to the dataset:<name> route for you:
import { useDataset } from '@/lib/analytics'; function OrdersRollup() { const { data, isLoading } = useDataset('orders', { dimensions: ['country', 'status'], measures: ['revenue', 'orderCount'], filters: [{ field: 'status', operator: 'eq', value: 'completed' }], limit: 25, }); if (isLoading) return <div>Loading...</div>; return ( <table> <tbody> {data?.data.map((row, i) => ( <tr key={i}> <td>{row.country}</td> <td>{row.status}</td> <td>{row.revenue}</td> <td>{row.orderCount}</td> </tr> ))} </tbody> </table> ); }
Both hooks validate against the server-side contract: an invalid dimension, measure, or filter returns a 400 error you can handle the same way as any other query. For cursor-free pagination, see useInfiniteDataset.
Rows contain the fields you selected. Measure values arrive as strings (or null) so decimals keep their precision;
convert them with a decimal library rather than Number(...) when exact arithmetic matters.
Pass includeMeta: true to also receive meta with requestId, timingMs, rowCount and
pagination: { limit, offset, hasMore }.
useMetric
useMetric queries a metric endpoint: one measure, optionally grouped by dimensions or a time grain. It takes the same
input as useDataset without measures or having, and each row carries the metric under its name:
import { useMetric } from '@/lib/analytics'; function MonthlyRevenue() { const { data } = useMetric('revenue', { by: 'month', filters: [{ field: 'createdAt', operator: 'between', value: ['2026-01-01T00:00:00Z', '2026-03-31T23:59:59Z'] }], orderBy: [{ field: 'period', direction: 'asc' }], }); return ( <ul> {data?.data.map((row) => ( <li key={row.period}>{row.period}: {row.revenue}</li> ))} </ul> ); }
With by, each row also has period, the start of its time bucket. useInfiniteMetric pages through a metric the same
way useInfiniteDataset pages through a dataset.
For a TypeScript backend, pass metrics to createAnalyticsHooks to limit which names useMetric accepts. A client
generated from a Python backend already knows its metric endpoints.
Error Handling
Failed requests reject with an HttpError, exported from @hypequery/react. It has the HTTP status and the parsed
response body; for hypequery endpoints the body is { error: { type, message, details? } }. error.message itself is
a generic description of the failed request, so read the server's message from the body:
import { HttpError } from '@hypequery/react'; type ServerError = { error?: { type?: string; message?: string; details?: { code?: string } } }; function errorMessage(error: unknown): string { if (!(error instanceof HttpError)) return 'Network error. Please check your connection.'; const server = (error.body as ServerError | null)?.error; if (error.status === 409 && server?.details?.code === 'CLIENT_SCHEMA_CHANGED') { return 'This page is out of date. Reload to get the latest version.'; } if (error.status === 400) return `Invalid query: ${server?.message ?? 'check the request'}`; if (error.status === 401 || error.status === 403) return 'You are not allowed to see this data.'; return `Something went wrong (${error.status}).`; } const { error } = useQuery('weeklyRevenue', { startDate: '2025-01-01' }); if (error) return <div>{errorMessage(error)}</div>;
body is typed unknown because servers and proxies can return any payload; narrow it before reading fields.
A 409 with CLIENT_SCHEMA_CHANGED comes from clients generated from a Python backend: the server's definitions changed
after the client was generated. Retrying cannot succeed. Regenerate the client and redeploy the frontend; see
Datasets served from Python.
Queries without input
For a query that takes no input, pass TanStack options as the second argument. If the call could be read as input,
wrap the options in queryOptions so the hook treats them as options:
import { queryOptions } from '@hypequery/react'; const { data } = useQuery('activeUsers', queryOptions({ enabled: isSignedIn }));
Common Patterns
Dependent Queries
Execute queries in sequence:
function UserRevenue({ userId }: { userId: string }) { const { data: user } = useQuery('getUser', { userId }); const { data: revenue } = useQuery( 'userRevenue', { userId }, { enabled: !!user } // Only run after user is loaded ); return <div>{revenue?.total}</div>; }
Polling
Automatically refetch data at intervals:
const { data } = useQuery( 'liveMetrics', {}, { refetchInterval: 5000 } // Poll every 5 seconds );
Manual Refetch
Trigger refetch on demand:
function MetricsPanel() { const { data, refetch } = useQuery('metrics', {}); return ( <div> <div>{data?.total}</div> <button onClick={() => refetch()}>Refresh</button> </div> ); }