tRPC
A todo list backed by a tRPC router. The router runs inside the Vite dev server through Hono, and the React app calls
its queries and mutations with useFetch and useSubmit. Every input, output and error type comes from the router.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";
import { client, sdk, todoListsKey } from "./api";
const filters = ["all", "open", "done"] as const;
export const App = () => {
const [status, setStatus] = useState<(typeof filters)[number]>("all");
const [title, setTitle] = useState("");
// The input is the payload. Each filter is cached on its own, so switching back is instant.
const { data, error, loading } = useFetch(sdk.todos.list.$query.setPayload({ status }));
const add = useSubmit(sdk.todos.add.$mutation);
const toggle = useSubmit(sdk.todos.toggle.$mutation);
// A change affects every filter, so invalidate all cached inputs of `todos.list` at once.
const refreshLists = () => client.cache.invalidate(todoListsKey);
add.onSubmitSuccess(() => {
setTitle("");
refreshLists();
});
toggle.onSubmitSuccess(refreshLists);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
add.submit({ payload: { title } });
};
// Procedure errors carry `data` with the router's `errorFormatter` fields. Network failures are plain `Error`s.
const titleError = add.error && "data" in add.error ? add.error.data.fieldErrors?.title : undefined;
return (
<main className="container">
<hgroup>
<h1>tRPC todos</h1>
<p>A tRPC router served by Hono, called through HyperFetch with types inferred from the router.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder="New todo"
aria-invalid={titleError ? true : undefined}
/>
<button type="submit" aria-busy={add.submitting} disabled={add.submitting}>
Add
</button>
</fieldset>
{add.error && <small className="error">{titleError ?? add.error.message}</small>}
</form>
<article>
<header className="toolbar">
<div role="group">
{filters.map((filter) => (
<button
key={filter}
type="button"
className={filter === status ? undefined : "outline"}
onClick={() => setStatus(filter)}
>
{filter}
</button>
))}
</div>
{/* A visited filter renders from the cache with no request, until a mutation invalidates it. */}
<small className="muted" aria-busy={loading}>
{loading ? "Fetching" : "Cached"}
</small>
</header>
{error && <p className="error">Could not load todos: {error.message}</p>}
{!data && loading && <p aria-busy="true">Loading todos...</p>}
<ul className="list">
{data?.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
disabled={toggle.submitting}
onChange={() => toggle.submit({ payload: { id: todo.id } })}
/>
{todo.title}
</label>
</li>
))}
{data?.length === 0 && <li className="muted">Nothing here.</li>}
</ul>
</article>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/trpc/basic hyper-fetch-trpc-basic && cd hyper-fetch-trpc-basic && npm install && npm run devTrpcAdaptersends requests in the tRPC format: queries asGET, mutations asPOST.TrpcSchema<AppRouter>turns the router type into a typed SDK, with$queryand$mutationfor each procedure.- The input is the payload, and every input has its own cache key, so each filter is cached separately.
- Typed errors: the router's
errorFormatteraddsfieldErrors, and the client sees them with their types.
How it works
-
server/router.tsis a regular tRPC v11 router withtodos.list,todos.addandtodos.toggle, validated with zod. It exportsAppRouter, the only thing the client imports, and only as a type. -
server/app.tsmounts the router in Hono with tRPC's fetch adapter.vite.config.tsruns that Hono app for every/apirequest, sonpm run devstarts the API and the client together:new Hono().all("/api/trpc/*", (c) =>fetchRequestHandler({endpoint: "/api/trpc",req: c.req.raw,router: appRouter,}),); -
src/api.tspoints the client at/api/trpc, setsTrpcAdapter()and builds the SDK:const client = createClient({url: `${window.location.origin}/api/trpc`,}).setAdapter(TrpcAdapter());const sdk = createSdk<typeof client, TrpcSchema<AppRouter>>(client, {camelCaseToKebabCase: false,});camelCaseToKebabCase: falsekeeps the procedure names as the router spells them.sdk.todos.list.$queryis a request fortodos.list. -
Apppasses the procedure input as the payload:useFetch(sdk.todos.list.$query.setPayload({ status })). The adapter adds the input to the cache key, soall,openanddoneare three cache entries. Switch back to a filter you already opened and it renders without a request. -
The mutations run through
useSubmit. After one succeeds,client.cache.invalidate(/^QUERY_todos\.list/)marks every cachedtodos.listinput stale, and the mounted list fetches again. -
Type a title shorter than three characters. zod rejects it, the router's
errorFormatteraddsfieldErrors: { title: "..." }, and the form shows it. A network failure has nodata, which is why the code checks"data" in add.errorfirst.
- You already have a tRPC backend and want caching, queueing, offline support or HyperFetch hooks on the client.
- One client for tRPC, REST and GraphQL, with the same request API for all of them.
- Any server that speaks the Fetch API can host the router: Hono, Next.js route handlers, Bun, Deno or Workers.
Related
TrpcAdapter speaks the tRPC protocol and TrpcSchema reads the router type, so createSdk gives you a typed request
for every query and mutation. They work with the usual hooks and cache, keyed by the procedure input.
