# Using Queries (/docs/react/using-queries)

Once you've set up `@hypequery/react`, you can use `useQuery` and `useMutation` in your components with full type safety.

## `useQuery` [#usequery]

Fetch data from your hypequery API with automatic caching and refetching:

<CodeBlock>
<Pre>
```tsx
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>;
}
```
</Pre>
</CodeBlock>

### Type Safety [#type-safety]

The query name and input are fully typed:

<CodeBlock>
<Pre>
```tsx
// ✅ 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',
});
```
</Pre>
</CodeBlock>

### TanStack Query Options [#tanstack-query-options]

All TanStack Query options are supported:

<CodeBlock>
<Pre>
```tsx
const { data } = useQuery('weeklyRevenue',
  { startDate: '2025-01-01' },
  {
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchOnWindowFocus: false,
    enabled: isAuthenticated, // Conditional fetching
  }
);
```
</Pre>
</CodeBlock>

## `useMutation` [#usemutation]

Execute write operations or actions:

<CodeBlock>
<Pre>
```tsx
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>
  );
}
```
</Pre>
</CodeBlock>

### Handling Success and Errors [#handling-success-and-errors]

<CodeBlock>
<Pre>
```tsx
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);
  },
});
```
</Pre>
</CodeBlock>

### Optimistic Updates [#optimistic-updates]

<CodeBlock>
<Pre>
```tsx
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'] });
  },
});
```
</Pre>
</CodeBlock>

## `useDataset` [#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:

<CodeBlock>
<Pre>
```tsx
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>
  );
}
```
</Pre>
</CodeBlock>

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`](/docs/react/advanced-patterns#infinite-queries).

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]

`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:

<CodeBlock>
<Pre>
```tsx
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>
  );
}
```
</Pre>
</CodeBlock>

With `by`, each row also has `period`, the start of its time bucket. `useInfiniteMetric` pages through a metric the same
way [`useInfiniteDataset`](/docs/react/advanced-patterns#infinite-queries) 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 [#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:

<CodeBlock>
<Pre>
```tsx
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>;
```
</Pre>
</CodeBlock>

`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](/docs/react/getting-started#datasets-served-from-python).

## Queries without input [#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:

<CodeBlock>
<Pre>
```tsx
import { queryOptions } from '@hypequery/react';

const { data } = useQuery('activeUsers', queryOptions({ enabled: isSignedIn }));
```
</Pre>
</CodeBlock>

## Common Patterns [#common-patterns]

### Dependent Queries [#dependent-queries]

Execute queries in sequence:

<CodeBlock>
<Pre>
```tsx
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>;
}
```
</Pre>
</CodeBlock>

### Polling [#polling]

Automatically refetch data at intervals:

<CodeBlock>
<Pre>
```tsx
const { data } = useQuery(
  'liveMetrics',
  {},
  { refetchInterval: 5000 } // Poll every 5 seconds
);
```
</Pre>
</CodeBlock>

### Manual Refetch [#manual-refetch]

Trigger refetch on demand:

<CodeBlock>
<Pre>
```tsx
function MetricsPanel() {
  const { data, refetch } = useQuery('metrics', {});

  return (
    <div>
      <div>{data?.total}</div>
      <button onClick={() => refetch()}>Refresh</button>
    </div>
  );
}
```
</Pre>
</CodeBlock>
