---
name: integrate-suspense-queries
description: >
  Wire Suspense-based loading UX over a generated full-mode client so a UI
  never shows an empty state while data is loading. Covers the per-endpoint
  queryOptions / useSuspenseQuery / fetch surface, the emitted ApiStatusError,
  route-loader priming with ensureQueryData, useSuspenseQueries for multiple
  queries, QueryErrorResetBoundary + error boundary + Suspense composition,
  skeleton fallbacks that mirror the real layout, 404 -> router notFound()
  in render, useDeferredValue for search-param pagination, and mapping
  documented error codes to product screens. Load when adding suspense
  loading, skeletons, or error boundaries over a full-mode client in a
  TanStack Router/Query v5 app.
type: framework
library: openapi-client-generator
library_version: "3.1.0"
requires:
  - generate-client
  - integrate-full-client
sources:
  - "bazo/openapi-client-generator:src/modes/full/query.ts"
  - "bazo/openapi-client-generator:src/modes/full/index.ts"
  - "bazo/openapi-client-generator:src/modes/shared/response-cases.ts"
---

This skill builds on generate-client (CLI) and integrate-full-client (client
instantiation, `useQuery`/`useMutation`). Read those first.

# Integrate Suspense Queries

## When to use

Reach for this when a TanStack Router + React Query v5 app consumes a
full-mode client and you want Suspense-driven loading — the rule **"never
show an empty state while loading"**. The failure mode it fixes: components
that narrow the response union with a pending-unsafe default
(`data?.status === 200 ? … : []`) flash empty lists while the request is in
flight, and errors never reach a boundary because nothing throws.

The full-mode client (v3.1.0+) emits, per query endpoint and *in addition* to
the unchanged legacy `query`/`useQuery`, a throwing surface that pairs with
Suspense and error boundaries. Legacy and suspense hooks share the **same
cache key**, so migration is incremental — a route can prime the cache in a
loader while some components still use `useQuery`.

## The emitted surface

For a query operation `getTask(taskId)` the client exposes:

```typescript
// legacy (unchanged) — resolves the status union, never throws
api.getTask.query({ taskId });
api.getTask.useQuery({ taskId });

// suspense surface (new)
api.getTask.queryOptions({ taskId });          // { queryKey, queryFn }
api.getTask.useSuspenseQuery({ taskId });       // hook — data is the payload
api.getTask.fetch({ taskId });                  // throwing promise, non-hook

// emitted once per file
export class ApiStatusError extends Error { status; data; code?; headers; url; cause? }
```

Behavior that shapes every recipe below:

- **`queryOptions(params?)`** returns `{ queryKey: ["getTask", params], queryFn }`
  — the key is byte-identical to legacy `useQuery`'s (`["opId"]` with no
  params, `["opId", params]` with). Its `queryFn` resolves the **success
  envelope** `{ status, data, headers, url }` and **throws `ApiStatusError`**
  for every documented non-2xx response whose body validates. The error's
  schema is looked up exact status → `4XX`-style range → `default` and applied
  strictly: a matching body populates `ApiStatusError.data` / `.code`; a body
  that breaks it (an HTML 500 from a proxy, an envelope with an undeclared key)
  rejects with **`ResponseValidationError`** instead — `status`, `headers`,
  `url`, raw `body`, and the ZodError / JSON SyntaxError as `cause`. A 2xx body
  that breaks its schema rejects with the same error. Only a status nothing
  documents, and network failures, pass through as the raw `WretchError`.
- **`useSuspenseQuery(params?, options?)`** wraps TanStack's hook with a
  hard-coded `select` that unwraps the envelope, so the hook's `data` **is the
  inner success payload** (`Task`, not `{ status, data, … }`). `.invalidate()`
  and `.key` are augmented on the result, exactly like legacy `useQuery`.
- **`fetch`** is the throwing promise API for non-hook use.

Source: src/modes/full/query.ts generateQueryOperation, src/modes/full/index.ts generateSuspenseHelpers

## Core Patterns

Router context is assumed to carry `{ client, queryClient }` (set once in the
root route). Every recipe reads the client from context, never a module import.

### (a) Prime the query in the route loader (non-awaited)

```typescript
export const Route = createFileRoute("/tasks/$taskId")({
  loader: ({ context: { queryClient, client }, params: { taskId } }) => {
    // void — do NOT await. Navigation commits instantly and Suspense owns the
    // loading UI. ensureQueryData writes the same key useSuspenseQuery reads.
    void queryClient.ensureQueryData(client.getTask.queryOptions({ taskId }));
  },
});
```

The non-awaited `void` is deliberate: an awaited loader blocks navigation and
you get no skeleton. Because the loader does not `await`, it also cannot
`catch` — error handling (including 404, recipe (e)) happens in render.

### (b) Consume it in the component — data is the payload

```tsx
function TaskDetail() {
  const { taskId } = Route.useParams();
  const { data: task } = api.getTask.useSuspenseQuery({ taskId });
  // `task` is the Task payload directly — the select already unwrapped the envelope.
  return <h1>{task.title}</h1>;
}
```

### (c) Multiple queries — `useSuspenseQueries` (results are envelopes)

Sequential `useSuspenseQuery` calls waterfall on a cold cache. Fetch in
parallel with `useSuspenseQueries`, feeding it the generated `queryOptions`:

```tsx
const [tasksQ, meQ] = useSuspenseQueries({
  queries: [api.listTasks.queryOptions(), api.getCurrentUser.queryOptions()],
});
// GOTCHA: the hard-coded select lives in useSuspenseQuery, NOT in queryOptions.
// So here each result.data is the ENVELOPE, not the payload:
const tasks = tasksQ.data.data;   // .data (query result) -> .data (envelope payload)
const me = meQ.data.data;
```

Read `.data` off each result to get the envelope, then `.data` again for the
payload. This is the single most common mistake when moving from single-query
to multi-query suspense.

### (d) Boundary composition

One boundary per data region. Static chrome (headings, tab nav, create button)
renders outside it. The v5 canonical composition wires the error boundary's
reset to `QueryErrorResetBoundary`:

```tsx
function QueryBoundary({ children, fallback, renderError, resetKeys }) {
  return (
    <QueryErrorResetBoundary>
      {({ reset }) => (
        <ErrorBoundary onReset={reset} resetKeys={resetKeys} fallback={renderError}>
          <Suspense fallback={fallback}>{children}</Suspense>
        </ErrorBoundary>
      )}
    </QueryErrorResetBoundary>
  );
}
```

- `fallback` is a **skeleton that mirrors the real layout** — real translated
  column headers / card shells, gray bars only where data lands. Never a
  centered spinner; that reintroduces layout shift.
- Tune the query client's retry so documented API errors reach the boundary
  immediately instead of being retried:

```typescript
const isApiStatusError = (e: unknown): e is ApiStatusErrorShape =>
  e instanceof Error && e.name === "ApiStatusError";

new QueryClient({
  defaultOptions: {
    queries: { retry: (count, error) => !isApiStatusError(error) && count < 1 },
  },
});
```

### (e) 404 -> router `notFound()` — in render, never in the loader

Map a documented 404 to the router's not-found UI from the boundary's
`renderError` (or a dedicated render branch), because the non-awaited loader
cannot throw it. Also **re-throw a router `notFound()` a child already threw**
(`isNotFound(error)`) — a child can derive "missing" from a loaded list and
`throw notFound()` during render, which lands in this same error boundary; if
`renderError` doesn't re-throw it, the class boundary swallows it into a retry
card:

```tsx
import { isNotFound, notFound } from "@tanstack/react-router";

function renderError(error: unknown, retry: () => void) {
  // documented API 404, OR a router notFound() a child threw in render
  if ((isApiStatusError(error) && error.status === 404) || isNotFound(error)) {
    throw notFound(); // router's CatchNotFound handles it — works warm, cold, and on param change
  }
  return <QueryErrorCard onRetry={retry} />;
}
```

The throw only reaches a not-found screen if a route in the matched chain
defines its **own** `notFoundComponent` — see the constraint below.

### (f) Pagination / filter changes — `useDeferredValue` on the search param

Move page/filter state to route search params (`validateSearch` +
`loaderDeps`). But router search updates ride `useSyncExternalStore` and are
**not** React transitions — so a page change re-suspends straight to the
skeleton, wiping the old rows. Defer the search value inside the suspending
component so the previous page stays mounted while the next loads
(verified live):

```tsx
function TaskTable() {
  const { page } = Route.useSearch();
  const deferredPage = useDeferredValue(page);
  const isPending = page !== deferredPage;               // dim while the next page loads
  const { data } = api.listTasks.useSuspenseQuery({ page: deferredPage, pageSize: 25 });
  return (
    <div style={{ opacity: isPending ? 0.6 : 1, transition: "opacity 120ms" }}>
      {/* old rows stay visible — no skeleton flash on page change */}
    </div>
  );
}
```

### (g) Error as product state

Some documented errors are expected states, not failures. Map their
`ApiStatusError.code` (extracted from the body's `code` field) to a purpose-built
screen instead of a generic retry card:

```tsx
function renderError(error: unknown, retry: () => void) {
  if (isApiStatusError(error) && error.code === "expired-token") {
    return <TokenExpiredScreen />; // friendly product screen, no "retry" button
  }
  return <QueryErrorCard onRetry={retry} />;
}
```

## Constraints

### CRITICAL Never `instanceof ApiStatusError` across modules

`ApiStatusError` is emitted **once per generated file**. A shared helper (or a
second generated client) sees a *different* class object, so `instanceof`
silently returns false across module/app boundaries.

Wrong:

```typescript
if (error instanceof ApiStatusError) { /* false across files */ }
```

Correct:

```typescript
if (error instanceof Error && error.name === "ApiStatusError") { /* stable */ }
```

Source: src/modes/full/index.ts generateSuspenseHelpers (`name = "ApiStatusError"`)

### CRITICAL Never resolve documented error statuses in a wretch catcher

Cache-key compatibility with legacy `useQuery` is guaranteed — same key, and
on every reachable path the two `queryFn`s cache the identical success
envelope. That guarantee **breaks** the moment an app adds a wretch
`.catcher()` / `.resolve()` that turns a documented non-2xx into a *resolved*
value: the legacy `useQuery` would then cache a fake success while the suspense
`fetch` still throws, so the two diverge on a shared endpoint's cache entry.

Wrong:

```typescript
// makes legacy useQuery resolve a 404 into the union — suspense fetch still throws → cache split
onHttpConfigure: (w) => w.resolve((r) => r.notFound(() => ({ status: 404, data: null })))
```

Keep documented non-2xx *throwing* (the default), and let the boundary /
`renderError` handle them.

Source: src/modes/full/query.ts (fetchFn throws; legacy queryFn resolves the union)

### HIGH Loader and hook params must be identical

`ensureQueryData(client.x.queryOptions(P))` and `client.x.useSuspenseQuery(Q)`
only share a cache entry when `P` and `Q` serialize equal — the key embeds the
params object. Diverging params split the key: the loader primes one entry, the
hook suspends on another (double fetch, skeleton flash). Derive both from one
shared const / the same `Route.useSearch()`+`loaderDeps` value.

Source: src/modes/full/query.ts (queryKey: `["opId", params]`)

### HIGH Every route that can throw `notFound()` in render needs its OWN `notFoundComponent`

TanStack Router only installs its `CatchNotFound` boundary for a match when
that route defines its own `notFoundComponent`. The router-level
`defaultNotFoundComponent` is **not** consulted for a `notFound()` thrown
during render (it only covers loader-thrown / no-match not-found) — so a route
that relies on the `renderError` 404→`notFound()` mapping (recipe (e)), or on a
child deriving a miss from a loaded list, will fall through to the default
error screen unless the route sets `notFoundComponent` explicitly:

```tsx
export const Route = createFileRoute("/tasks/$taskId")({
  component: TaskDetail,
  notFoundComponent: () => <NotFoundScreen … />, // installs CatchNotFound for this match
});
```

Put it on the match that owns the boundary. For a layout route whose heading
suspends in a bare `<Suspense>` (no QueryBoundary), a 404 there surfaces as the
raw `ApiStatusError` on the match's error boundary, not a `notFound()` — handle
it with an `errorComponent` that renders the not-found screen when
`isApiStatusError(error) && error.status === 404`, and keep `notFoundComponent`
for the render-thrown path from the tab content below.

## Reference implementation

dentistmax `ui/admin` is the tuned reference — search-param pagination,
per-region `QueryBoundary`, layout-mirroring panel skeletons, and the
404/error-as-product-state split. See `docs/suspense-loading.md` there for the
migration blueprint (envelope-narrowing root cause, queryKey-compat rationale,
transition pagination findings) before applying this to another app.

See also: generate-client/SKILL.md — CLI usage for regenerating the client
See also: integrate-full-client/SKILL.md — client instantiation, legacy useQuery/useMutation
