---
title: Overlays + Async Data (React Query)
description: Render a Sheet, Dialog, or Alert Dialog immediately, then swap its body between pending, success, 404, and 500 states with TanStack Query.
---

# Overlays + Async Data (React Query)

Opening a floating overlay (a [`Sheet`](/components/overlays/sheet), a [`Dialog`](/components/overlays/dialog), or an [`AlertDialog`](/components/overlays/alert-dialog)) is a navigation: the user has already committed to seeing more context by clicking the trigger. When the overlay's body needs remote data, fetching before opening turns a 404 or 500 into a silent drop back to the parent view, and a spinner on the trigger leaves the click feeling unregistered. This recipe mounts the shell immediately and resolves data inside it, so every click produces forward motion and every error stays in the place the user navigated to.

The pattern is identical across all three overlays: only the shell changes. The query hook, the body-state components, and the retry policy below are shared verbatim; the demo lets you host them in any of the three shells.

> \[!IMPORTANT]
> Don't copy this UI verbatim. This recipe teaches how to **reason about asynchronous server state** (mount the shell on the click, branch only the body, encode the retry policy, gate actions on success) so the overlay paints immediately and perceived loading time stays low. The user-details layout, copy, and demo controls are deliberately plain stand-ins (the dialog and alert-dialog bodies in particular are not layouts you'd ship as-is); swap them for your product's real content and visual design, and keep the state structure.

Try it in the [live demo](#complete-recipe), directly above the code that renders it.

## Why open the overlay first?

- **The open should feel instant, especially on slow networks.** The user already committed to the navigation by clicking the trigger. Waiting for the request to resolve before opening means dead air at the parent view, and the wait scales with request latency: long-running endpoints or slow connections turn into seconds where users can't tell whether the click registered. Mounting the shell immediately decouples click feedback from request time.
- **No flashing across the open → load → close → reopen cycle.** Within a single open, only the overlay's `Body` region branches between pending, success, and error, so header, close, and footer stay mounted and layout shift is contained to one region. Across opens, TanStack Query's cache lets a re-trigger after a successful fetch skip the pending state entirely; fetch-then-open does the opposite, re-running the request on every trigger and flashing the chrome in only after each fetch resolves.
- **Errors stay where the user intended to be.** An inline error inside the overlay preserves the navigation and keeps recovery actions in reach. Closing on error forces a re-trigger and re-orientation from the parent view.
- **Actions gate on data, not hope.** The footer's primary action ("Save changes" in a sheet or dialog, the destructive confirm in an alert dialog) stays disabled until the query succeeds. This matters most for `AlertDialog`: confirming a destructive action against a record that failed to load is never safe.
- **Retry is a product decision, not a default.** Transient `500` responses are worth another attempt; a definitive `404` is not. The query hook owns that policy so the view stays free of conditional retry logic and the intent stays reviewable in one place.

## What this covers

| Case       | Demo behavior                                                                     |
| ---------- | --------------------------------------------------------------------------------- |
| Happy path | Waits 1.5 seconds, then renders a loaded user profile.                            |
| 404 error  | Waits 1.5 seconds once, then renders a not-found empty state.                     |
| 500 error  | Waits 1.5 seconds per request, retries twice, then renders a service empty state. |

The demo's segmented control picks which shell hosts the async body; the same three scenarios run identically in a `Sheet`, a `Dialog`, and an `AlertDialog`.

The route is also available as plain markdown at [`/recipes/overlay-async.md`](/recipes/overlay-async.md), so humans and LLM tools can fetch the same recipe without scraping the rendered page.

## Anatomy

```text showLineNumbers=false
Parent selection state
└── Overlay shell: Sheet | Dialog | AlertDialog (mounted immediately)
    └── useUserQuery({ userId, scenario })
        ├── Header             stable
        ├── Body               pending | success | error   ← the only region that branches
        └── Footer             stable; gate actions on success
```

## Implementation

The "Why" section above is the user-perceived case for the pattern. These rules are how to wire it up so the code stays consistent with that intent.

1. **Mount the overlay on the click event.** Set selection state synchronously in the handler; never gate it on a fetch result.
2. **Branch only the body on query state.** `query.isPending`, `query.isError`, and `query.isSuccess` belong inside the overlay's `Body` region. Header, close button, and footer stay outside the conditional.
3. **Factor the query into a hook.** `useUserQuery` owns fetching, retry, stale-time, and cancellation. The components that render query results (the shells, `UserDetailsBody`) consume a `UseQueryResult` and never reach into TanStack Query directly. The cache-observability bits in `UserOverlayDemo` (the `useQueryClient` subscription and `removeQueries` reset) are demo-only; production overlays shouldn't touch the cache.
4. **Encode the retry policy in `useQuery`.** Return `false` from `retry` for terminal errors like `404`. Return a bounded `failureCount` check for transient ones like `500`.
5. **Match the retry UI to the retry policy.** Show a retry button on recoverable errors. Omit it on terminal ones: retrying a definitive not-found adds latency without recovery.

## Complete recipe

The worked example below uses `Sheet` as the shell; the [next section](#swapping-the-shell) shows the `Dialog` and `AlertDialog` shells consuming the exact same hook and body components. Copy the UI recipe into a client component that already has a `QueryClientProvider` mounted near the app root. The demo-only mock API is shown in the appendix below; in production, replace that import with your real API client and error type.

What transfers is the **structure**: the synchronous mount, the single branching region, the hook-owned retry policy, and the success-gated actions. What doesn't is the markup inside each state: `UserDetails`, the skeleton shapes, and the header/footer copy are demo content standing in for your real UI.

```tsx
import { Button } from "@ngrok/mantle/button";
import { DescriptionList } from "@ngrok/mantle/description-list";
import { Empty } from "@ngrok/mantle/empty";
import { MediaObject } from "@ngrok/mantle/media-object";
import { Separator } from "@ngrok/mantle/separator";
import { Sheet } from "@ngrok/mantle/sheet";
import { Skeleton } from "@ngrok/mantle/skeleton";
import { MagnifyingGlassIcon } from "@phosphor-icons/react/MagnifyingGlass";
import { SmileyMeltingIcon } from "@phosphor-icons/react/SmileyMelting";
import {
	useQuery,
	useQueryClient,
	type QueryClient,
	type UseQueryResult,
} from "@tanstack/react-query";
import { type ReactNode, useEffect, useState } from "react";
import {
	fetchUser,
	RequestCancelledError,
	UserRequestError,
	type User,
	type UserRequestScenario,
} from "./mock-user-api";

const SERVER_ERROR_RETRY_LIMIT = 2;
const USER_QUERY_RETRY_DELAY_MS = 500;
const USER_QUERY_KEY_ROOT = ["overlay-async-user"];

const scenarioLabels: Record<UserRequestScenario, string> = {
	success: "happy path",
	"not-found": "404",
	"server-error": "500",
};

/** Props shared by every controlled async overlay shell. */
type UserOverlayProps = {
	/** User identifier requested by the overlay. */
	userId: string;
	/** Demo scenario selected by the user. */
	scenario: UserRequestScenario;
	/** Called when the user dismisses the overlay. */
	onClose: () => void;
};

/** Renders immediately, then swaps the sheet body from pending to success or error. */
export function UserSheet({ onClose, scenario, userId }: UserOverlayProps) {
	const query = useUserQuery({ scenario, userId });

	return (
		<Sheet.Root
			open
			onOpenChange={(nextOpen) => {
				if (!nextOpen) {
					onClose();
				}
			}}
		>
			<Sheet.Content preferredWidth="sm:max-w-136">
				<Sheet.Header>
					<Sheet.TitleGroup>
						<Sheet.Title>User details</Sheet.Title>
						<Sheet.Actions>
							<Sheet.CloseIconButton />
						</Sheet.Actions>
					</Sheet.TitleGroup>
					<Sheet.Description>
						Loading <span className="font-mono">{userId}</span> through the{" "}
						{scenarioLabels[scenario]} case.
					</Sheet.Description>
				</Sheet.Header>
				<Sheet.Body>
					<UserDetailsBody query={query} />
				</Sheet.Body>
				<Sheet.Footer>
					<Sheet.Close asChild>
						<Button type="button" appearance="outlined" intent="neutral">
							Close
						</Button>
					</Sheet.Close>
					<Button type="button" appearance="filled" intent="neutral" disabled={!query.isSuccess}>
						Save changes
					</Button>
				</Sheet.Footer>
			</Sheet.Content>
		</Sheet.Root>
	);
}

/** Props for selecting which body state to render. */
type UserDetailsBodyProps = {
	/** TanStack Query result that drives the body state. */
	query: UseQueryResult<User, Error>;
};

/** Keeps the overlay chrome stable while only the body content changes. */
function UserDetailsBody({ query }: UserDetailsBodyProps) {
	if (query.isPending) {
		return <UserDetailsLoading failureCount={query.failureCount} />;
	}

	if (query.isError) {
		return (
			<UserDetailsError
				error={query.error}
				isRetrying={query.isFetching}
				onRetry={() => {
					void query.refetch();
				}}
			/>
		);
	}

	if (query.isSuccess) {
		return <UserDetails user={query.data} />;
	}

	return null;
}

/** Props for the loading state. */
type UserDetailsLoadingProps = {
	/** Failed attempts observed while TanStack Query is still retrying. */
	failureCount: number;
};

/** Mirrors the successful layout so the overlay body does not jump when data arrives. */
function UserDetailsLoading({ failureCount }: UserDetailsLoadingProps) {
	return (
		<div className="space-y-4" aria-busy="true" aria-label="Loading user details">
			<MediaObject.Root className="items-center">
				<MediaObject.Media>
					<Skeleton className="size-12 rounded-full" />
				</MediaObject.Media>
				<MediaObject.Content className="space-y-2">
					<Skeleton className="h-4 w-40" />
					<Skeleton className="h-3 w-56" />
				</MediaObject.Content>
			</MediaObject.Root>
			<Separator />
			<div className="space-y-2">
				<Skeleton className="h-3 w-full" />
				<Skeleton className="h-3 w-5/6" />
				<Skeleton className="h-3 w-3/4" />
			</div>
			{failureCount > 0 && (
				<p className="text-sm text-muted" role="status">
					Retrying after {failureCount} failed {failureCount === 1 ? "attempt" : "attempts"}.
				</p>
			)}
		</div>
	);
}

/** Props for the inline error state. */
type UserDetailsErrorProps = {
	/** Error thrown by the query function. */
	error: Error;
	/** Whether a manual retry is currently in flight. */
	isRetrying: boolean;
	/** Called when the user requests another attempt. */
	onRetry: () => void;
};

/** Renders a recoverable inline error instead of closing the overlay. */
function UserDetailsError({ error, isRetrying, onRetry }: UserDetailsErrorProps) {
	const copy = getUserErrorCopy(error);

	return (
		<Empty.Root className="py-8">
			<Empty.Icon svg={copy.icon} />
			<Empty.Title className="text-lg">{copy.title}</Empty.Title>
			<Empty.Description>
				<p>{copy.description}</p>
				{copy.requestId && (
					<p>
						Request ID <span className="font-mono text-strong">{copy.requestId}</span>
					</p>
				)}
			</Empty.Description>
			{copy.canRetry && (
				<Empty.Actions>
					<Button
						type="button"
						appearance="filled"
						intent="danger"
						isLoading={isRetrying}
						onClick={onRetry}
					>
						Retry request
					</Button>
				</Empty.Actions>
			)}
		</Empty.Root>
	);
}

/** Copy values shown by the inline error state. */
type UserErrorCopy = {
	/** Whether the Empty state should render a retry action. */
	canRetry: boolean;
	/** Icon shown by the Empty state. */
	icon: ReactNode;
	/** Short Empty state title. */
	title: string;
	/** Human-readable remediation context. */
	description: string;
	/** Optional request id shown for support workflows. */
	requestId?: string;
};

/** Converts typed request errors into user-facing copy. */
function getUserErrorCopy(error: Error): UserErrorCopy {
	if (error instanceof UserRequestError && error.status === 404) {
		return {
			canRetry: false,
			icon: <MagnifyingGlassIcon />,
			title: "User not found",
			description: "The request completed, but no user exists for that id.",
			requestId: error.requestId,
		};
	}

	if (error instanceof UserRequestError && error.status === 500) {
		return {
			canRetry: true,
			icon: <SmileyMeltingIcon />,
			title: "User service unavailable",
			description:
				"The service failed after retrying. Keep the overlay open so the user can try again.",
			requestId: error.requestId,
		};
	}

	return {
		canRetry: true,
		icon: <SmileyMeltingIcon />,
		title: "Could not load user",
		description: error.message || "An unknown error occurred.",
	};
}

/** Props for the successful user details state. */
type UserDetailsProps = {
	/** Loaded user data returned by the query. */
	user: User;
};

/** Renders the successful data state. */
function UserDetails({ user }: UserDetailsProps) {
	return (
		<div className="space-y-4">
			<MediaObject.Root className="items-center">
				<MediaObject.Media>
					<div className="flex size-12 items-center justify-center rounded-full bg-accent-500 font-mono text-on-filled">
						{user.name[0]}
					</div>
				</MediaObject.Media>
				<MediaObject.Content>
					<p className="font-medium text-strong">{user.name}</p>
					<p className="text-sm text-muted">{user.email}</p>
				</MediaObject.Content>
			</MediaObject.Root>
			<Separator />
			<DescriptionList.Root>
				<DescriptionList.Item>
					<DescriptionList.Label>ID</DescriptionList.Label>
					<DescriptionList.Value>{user.id}</DescriptionList.Value>
				</DescriptionList.Item>
				<DescriptionList.Item>
					<DescriptionList.Label>Role</DescriptionList.Label>
					<DescriptionList.Value>{user.role}</DescriptionList.Value>
				</DescriptionList.Item>
				<DescriptionList.Item>
					<DescriptionList.Label>Workspace</DescriptionList.Label>
					<DescriptionList.Value>{user.workspace}</DescriptionList.Value>
				</DescriptionList.Item>
				<DescriptionList.Item>
					<DescriptionList.Label>Plan</DescriptionList.Label>
					<DescriptionList.Value>{user.plan}</DescriptionList.Value>
				</DescriptionList.Item>
				<DescriptionList.Item>
					<DescriptionList.Label>Joined</DescriptionList.Label>
					<DescriptionList.Value>{user.joinedAt}</DescriptionList.Value>
				</DescriptionList.Item>
				<DescriptionList.Item>
					<DescriptionList.Label>Last active</DescriptionList.Label>
					<DescriptionList.Value>{user.lastActiveAt}</DescriptionList.Value>
				</DescriptionList.Item>
			</DescriptionList.Root>
		</div>
	);
}

/** Selected overlay state owned by the parent list/page. */
type SelectedUserOverlay = {
	/** User identifier requested by the overlay. */
	userId: string;
	/** Demo scenario selected by the user. */
	scenario: UserRequestScenario;
};

/** Query key for the success scenario, used to observe and clear only the happy-path cache entry. */
const HAPPY_PATH_QUERY_KEY = [...USER_QUERY_KEY_ROOT, userIdForScenario("success"), "success"];

/** Tracks whether the happy-path query has a successful response in the cache. The 404 and 500 scenarios throw, so they never reach a successful cache state. */
function useIsHappyPathCached(): boolean {
	const queryClient = useQueryClient();
	const [isCached, setIsCached] = useState(() => readIsHappyPathCached(queryClient));

	useEffect(() => {
		const cache = queryClient.getQueryCache();
		const unsubscribe = cache.subscribe((event) => {
			// Ignore cache events that don't touch the happy-path query so other consumers of the
			// QueryClient don't trigger a recompute on every cache mutation.
			if (!isHappyPathCacheEvent(event)) {
				return;
			}
			const next = readIsHappyPathCached(queryClient);
			setIsCached((prev) => (prev === next ? prev : next));
		});
		return unsubscribe;
	}, [queryClient]);

	return isCached;
}

/** Returns true when the happy-path query has a successful response in the cache. */
function readIsHappyPathCached(queryClient: QueryClient): boolean {
	const query = queryClient.getQueryCache().find({ queryKey: HAPPY_PATH_QUERY_KEY, exact: true });
	return query?.state.status === "success";
}

/** True when a query-cache event refers to the happy-path query key. */
function isHappyPathCacheEvent(event: { query: { queryKey: readonly unknown[] } }): boolean {
	const queryKey = event.query.queryKey;
	if (queryKey.length !== HAPPY_PATH_QUERY_KEY.length) {
		return false;
	}
	return queryKey.every((part, index) => part === HAPPY_PATH_QUERY_KEY[index]);
}

/** Builds the cache-state caption shown beneath the demo controls. */
function describeCacheState(isCached: boolean): string {
	if (isCached) {
		return `Happy path is cached. Reopening it now skips the pending state and renders the result immediately. Click "Clear cache" to reset.`;
	}
	return "No successful response is cached. Clicking happy path will fetch from scratch and show pending; closing the overlay keeps the result so reopening skips pending. The 404 and 500 scenarios throw, so reopening them always re-fetches.";
}

/** Opens the three async body states from parent-owned selection state. */
export function UserOverlayDemo() {
	const [selection, setSelection] = useState<SelectedUserOverlay | null>(null);
	const queryClient = useQueryClient();
	const isHappyPathCached = useIsHappyPathCached();

	/** Opens a fresh overlay for the selected demo case. */
	const openOverlay = (scenario: UserRequestScenario) => {
		setSelection({ scenario, userId: userIdForScenario(scenario) });
	};

	/** Dismisses the overlay without clearing the cache so reopening can demonstrate skip-pending. */
	const closeOverlay = () => {
		setSelection(null);
	};

	/** Removes every cached response so the next click shows the pending state again. */
	const clearCache = () => {
		queryClient.removeQueries({ queryKey: USER_QUERY_KEY_ROOT });
	};

	return (
		<div className="flex flex-col gap-3">
			<div className="flex flex-wrap items-center gap-2">
				<Button
					type="button"
					appearance="filled"
					intent="neutral"
					onClick={() => openOverlay("success")}
				>
					Happy path
				</Button>
				<Button
					type="button"
					appearance="outlined"
					intent="neutral"
					onClick={() => openOverlay("not-found")}
				>
					404 error
				</Button>
				<Button
					type="button"
					appearance="filled"
					intent="danger"
					onClick={() => openOverlay("server-error")}
				>
					500 error
				</Button>
			</div>
			<div className="flex flex-wrap items-center gap-2">
				<Button
					type="button"
					appearance="ghost"
					intent="neutral"
					onClick={clearCache}
					disabled={!isHappyPathCached}
				>
					Clear cache
				</Button>
			</div>
			<p className="text-sm text-muted" aria-live="polite">
				{describeCacheState(isHappyPathCached)}
			</p>
			{selection && (
				<UserSheet userId={selection.userId} scenario={selection.scenario} onClose={closeOverlay} />
			)}
		</div>
	);
}

/** Returns the user id that makes the selected scenario readable in the UI. */
function userIdForScenario(scenario: UserRequestScenario): string {
	if (scenario === "not-found") {
		return "user_missing";
	}

	return "user_01J8Q7Z5K2";
}

/** Options passed to the demo query hook. */
type UseUserQueryOptions = {
	/** User identifier requested by the overlay. */
	userId: string;
	/** Demo scenario selected by the user. */
	scenario: UserRequestScenario;
};

/** Fetches user details for the overlay with TanStack Query and an explicit retry policy. */
function useUserQuery({ scenario, userId }: UseUserQueryOptions): UseQueryResult<User, Error> {
	return useQuery<User, Error>({
		queryKey: [...USER_QUERY_KEY_ROOT, userId, scenario],
		queryFn: ({ signal }) => fetchUser({ userId, scenario, signal }),
		retry: (failureCount, error) => shouldRetryUserQuery({ error, failureCount }),
		retryDelay: USER_QUERY_RETRY_DELAY_MS,
		staleTime: 30_000,
		gcTime: 5 * 60_000,
	});
}

/** Options passed to the query retry policy. */
type ShouldRetryUserQueryOptions = {
	/** Number of failed attempts TanStack Query has observed. */
	failureCount: number;
	/** Error thrown by the query function. */
	error: Error;
};

/** Retries transient server failures while skipping terminal and cancelled requests. */
function shouldRetryUserQuery({ error, failureCount }: ShouldRetryUserQueryOptions): boolean {
	if (error instanceof RequestCancelledError) {
		return false;
	}

	if (error instanceof UserRequestError && error.status === 500) {
		return failureCount < SERVER_ERROR_RETRY_LIMIT;
	}

	return false;
}
```

## Swapping the shell

Everything above the shell (`useUserQuery`, `UserDetailsBody`, the loading/error/success components, the retry policy) is overlay-agnostic. To host the same async body in a different overlay, swap only the shell component. The live demo at the top of this page renders all three shells from the same parent selection state behind a segmented control.

### Dialog

The `Dialog` shell is a one-for-one structural swap with `Sheet`: header and footer stay mounted, only `Dialog.Body` branches, and the primary action gates on `query.isSuccess`.

```tsx
import { Button } from "@ngrok/mantle/button";
import { Dialog } from "@ngrok/mantle/dialog";

/** Renders immediately, then swaps the dialog body from pending to success or error. */
export function UserDialog({ onClose, scenario, userId }: UserOverlayProps) {
	const query = useUserQuery({ scenario, userId });

	return (
		<Dialog.Root
			open
			onOpenChange={(nextOpen) => {
				if (!nextOpen) {
					onClose();
				}
			}}
		>
			<Dialog.Content preferredWidth="max-w-xl">
				{/* Dialog.Header is a single flex row: Title + CloseIconButton only.
				    The description lives at the top of the Body (Radix wires
				    aria-describedby from anywhere inside Content). */}
				<Dialog.Header>
					<Dialog.Title>User details</Dialog.Title>
					<Dialog.CloseIconButton />
				</Dialog.Header>
				<Dialog.Body className="space-y-4">
					<Dialog.Description>
						Loading <span className="font-mono">{userId}</span> through the{" "}
						{scenarioLabels[scenario]} case.
					</Dialog.Description>
					<UserDetailsBody query={query} />
				</Dialog.Body>
				<Dialog.Footer>
					<Dialog.Close asChild>
						<Button type="button" appearance="outlined" intent="neutral">
							Close
						</Button>
					</Dialog.Close>
					<Button type="button" appearance="filled" intent="neutral" disabled={!query.isSuccess}>
						Save changes
					</Button>
				</Dialog.Footer>
			</Dialog.Content>
		</Dialog.Root>
	);
}
```

### AlertDialog

An `AlertDialog` confirms a consequential (usually destructive) action, which sharpens the pattern's stakes: the record the user is about to act on is exactly the thing being fetched. Two rules are non-negotiable here:

- **The destructive `Action` stays disabled until the query succeeds.** Confirming against a record that hasn't loaded (or definitively doesn't exist) is never safe. On a 404, the disabled action plus the inline not-found state is the correct terminal UI.
- **Errors never auto-close the confirmation.** The user chose to act; an inline error with a retry (for transient failures) keeps them in that intent instead of silently dropping it.

```tsx
import { AlertDialog } from "@ngrok/mantle/alert-dialog";

/**
 * Renders immediately and loads the record the user is about to act on. The
 * destructive action stays disabled until the data resolves.
 */
export function UserAlertDialog({ onClose, scenario, userId }: UserOverlayProps) {
	const query = useUserQuery({ scenario, userId });

	return (
		<AlertDialog.Root
			intent="danger"
			open
			onOpenChange={(nextOpen) => {
				if (!nextOpen) {
					onClose();
				}
			}}
		>
			<AlertDialog.Content preferredWidth="max-w-xl">
				<AlertDialog.Icon />
				<AlertDialog.Body>
					<AlertDialog.Header>
						<AlertDialog.Title>Remove this user?</AlertDialog.Title>
						<AlertDialog.Description>
							Review{" "}
							<span translate="no" className="font-mono">
								{userId}
							</span>{" "}
							before removing them (loaded through the {scenarioLabels[scenario]} case).
						</AlertDialog.Description>
					</AlertDialog.Header>
					<div className="mt-4">
						<UserDetailsBody query={query} />
					</div>
					<AlertDialog.Footer>
						<AlertDialog.Cancel type="button">Cancel</AlertDialog.Cancel>
						<AlertDialog.Action type="button" disabled={!query.isSuccess}>
							Remove user
						</AlertDialog.Action>
					</AlertDialog.Footer>
				</AlertDialog.Body>
			</AlertDialog.Content>
		</AlertDialog.Root>
	);
}
```

## Mock API appendix

The code above imports a mock API module so the overlays can demonstrate happy, 404, and 500 states without a backend. In production, replace this file with your real API client and preserve the same query behavior: accept `signal`, throw typed errors, and let the UI decide which errors are retryable.

```ts
const SIMULATED_USER_API_LATENCY_MS = 1_500;

/** Scenario names used by the docs demo controls. */
export type UserRequestScenario = "success" | "not-found" | "server-error";

/** The typed user record returned by the demo API. */
export type User = {
	/** Stable user identifier from the backend. */
	id: string;
	/** Display name shown in the overlay header content. */
	name: string;
	/** Primary email address for the account. */
	email: string;
	/** Role within the current workspace. */
	role: string;
	/** Workspace name used to make the example feel like app data. */
	workspace: string;
	/** Billing plan attached to the workspace. */
	plan: string;
	/** ISO date string for when the user joined. */
	joinedAt: string;
	/** Human-readable recent activity summary. */
	lastActiveAt: string;
};

/** The HTTP status codes intentionally simulated by the demo. */
type UserRequestErrorStatus = 404 | 500;

/** Options for constructing a typed demo request error. */
type UserRequestErrorOptions = {
	/** HTTP status returned by the simulated endpoint. */
	status: UserRequestErrorStatus;
	/** User-facing or operator-facing error message. */
	message: string;
	/** Request identifier included in the inline error UI. */
	requestId: string;
};

/** Error shape used when the simulated endpoint returns a non-2xx response. */
export class UserRequestError extends Error {
	/** HTTP status returned by the simulated endpoint. */
	readonly status: UserRequestErrorStatus;
	/** Request identifier included in the inline error UI. */
	readonly requestId: string;

	/** Creates a typed request error that preserves HTTP metadata. */
	constructor({ message, requestId, status }: UserRequestErrorOptions) {
		super(message);
		this.name = "UserRequestError";
		this.requestId = requestId;
		this.status = status;
	}
}

/** Error used when TanStack Query aborts a request after the overlay unmounts. */
export class RequestCancelledError extends Error {
	/** Creates a cancellation error that the retry policy can ignore. */
	constructor() {
		super("The user details request was cancelled.");
		this.name = "RequestCancelledError";
	}
}

/** Options for delaying the simulated API response. */
type WaitForDemoApiOptions = {
	/** Delay duration in milliseconds. */
	durationMs: number;
	/** Abort signal passed by TanStack Query. */
	signal?: AbortSignal;
};

/** Waits before resolving so the overlay can show the pending state. */
function waitForDemoApi({ durationMs, signal }: WaitForDemoApiOptions): Promise<void> {
	return new Promise((resolve, reject) => {
		if (signal?.aborted) {
			reject(new RequestCancelledError());
			return;
		}

		const timeoutId = setTimeout(() => {
			signal?.removeEventListener("abort", handleAbort);
			resolve();
		}, durationMs);

		/** Cancels the simulated API delay when the query unmounts. */
		function handleAbort() {
			clearTimeout(timeoutId);
			signal?.removeEventListener("abort", handleAbort);
			reject(new RequestCancelledError());
		}

		signal?.addEventListener("abort", handleAbort, { once: true });
	});
}

/** Options accepted by the simulated user fetcher. */
type FetchUserOptions = {
	/** User identifier requested by the overlay. */
	userId: string;
	/** Demo scenario selected by the user. */
	scenario: UserRequestScenario;
	/** Abort signal passed by TanStack Query. */
	signal?: AbortSignal;
};

/** Simulates a production API client with latency, typed data, and HTTP errors. */
export async function fetchUser({ scenario, signal, userId }: FetchUserOptions): Promise<User> {
	await waitForDemoApi({ durationMs: SIMULATED_USER_API_LATENCY_MS, signal });

	if (scenario === "not-found") {
		throw new UserRequestError({
			status: 404,
			message: `No user exists for ${userId}.`,
			requestId: createDemoRequestId({ status: 404, userId }),
		});
	}

	if (scenario === "server-error") {
		throw new UserRequestError({
			status: 500,
			message: "The user service failed before returning profile data.",
			requestId: createDemoRequestId({ status: 500, userId }),
		});
	}

	return {
		id: userId,
		name: "Ada Lovelace",
		email: "ada.lovelace@example.com",
		role: "Founding Engineer",
		workspace: "Analytical Engines",
		plan: "Enterprise",
		joinedAt: "1843-07-08",
		lastActiveAt: "2 minutes ago",
	};
}

/** Options for creating a deterministic request id in the demo. */
type CreateDemoRequestIdOptions = {
	/** HTTP status returned by the simulated endpoint. */
	status: UserRequestErrorStatus;
	/** User identifier requested by the overlay. */
	userId: string;
};

/** Creates a stable request id so the error UI looks like real production output. */
function createDemoRequestId({ status, userId }: CreateDemoRequestIdOptions): string {
	return `req_${status}_${userId.replace(/[^a-z0-9]/gi, "").slice(-8)}`;
}
```

## Production notes

- Keep each overlay shell in one component and keep API details behind `fetchUser` or your app's equivalent data client. The shell is the only overlay-specific code; everything else is shared.
- Use the `signal` argument from TanStack Query's `queryFn` when your API client supports cancellation.
- Tune `retry` by status code. This demo does not retry 404 because the server already answered definitively. Retry not-found responses only when eventual consistency is expected.
- Gate footer actions on `query.isSuccess`. For `AlertDialog` specifically, never enable the destructive `Action` while the query is pending or errored: the confirmation is only meaningful against loaded data.
- Let `staleTime` and `gcTime` govern cache lifetime; the overlay does not need to manually evict on close. The demo's "Clear cache" button only exists to make the cache state observable in docs; production overlays typically don't surface a manual reset.
- Prefer explicit query state branches here over `useSuspenseQuery`. Suspense works, but error recovery requires an additional reset boundary and is harder to copy into route-controlled overlays.
