Skip to main content

Examples

Every example is a small, complete app you can run in the browser, open in StackBlitz or CodeSandbox, or copy to your machine. Each one focuses on a single idea and explains what it shows and how it works.

How to use the examples
  1. Read the page to see what the example shows and which parts of HyperFetch it uses.
  2. Press Run example to start it in your browser, or open it in StackBlitz or CodeSandbox to edit it.
  3. Copy it locally with npx tiged BetterTyped/hyper-fetch/examples/<group>/<name> my-app.

The examples live in the examples/ folder of the repository. They are built and type-checked against the current source on every change, so the code you see here works with the latest release.

Getting started

Fetch a list and its details with useFetch, typed requests and a shared cache.

Send typed requests from plain TypeScript and read the response object, no framework needed.

Type endpoint and global errors, render a state per status and retry failed requests.

Typed SDKbeginner

Describe an API once as a typed schema and call it through createSdk with useFetch and useSubmit.

Change staleTime, cacheTime, retry and refetchOnFocus with sliders and watch the cache and the network react.

Set useFetch options once for the whole app with the React Provider, and override them per hook.

Custom hooksbeginner

Wrap requests in your own typed hooks, usePosts, usePost and useRenamePost, so components stay small.

Testingintermediate

Test a component that fetches and saves data with Vitest, Testing Library and HyperFetch mocks.

Data fetching

Fetch a user first, then load their posts and todos only once the user id is known.

Paginationintermediate

Page through products with query params, keep the previous page on screen and prefetch the next one.

Infinite scrollintermediate

Load the next page of products as you scroll, with useInfiniteFetch and an IntersectionObserver.

Load moreintermediate

Load pages on demand with a Load more button, start in the middle of a list and see where each page begins.

Search products while typing and send one request per pause with the bounce option of useFetch.

Pollingbeginner

Refetch data on an interval with refresh and refreshTime, and pause polling in background tabs.

Refetch on focusintermediate

Refetch when the window gets focus, loses it or the network comes back, with a log of every trigger.

Suspenseintermediate

Load data with React Suspense and handle failed requests in an error boundary with throwOnError.

Selectintermediate

Read different parts of one cached response with the select option, and re-render only when that part changes.

Prefetchingintermediate

Prefetch product details on hover with request.send(), so opening them shows cached data at once.

Load several independent requests at once, each with its own loading state, and show a global indicator with useIsFetching.

URL filtersintermediate

Keep search, sort and page in the URL query string and turn them into typed query params, with working back and forward.

Send a request only when the user asks: useFetch with disabled, or request.send() for a one-off call.

Max pagesadvanced

An infinite list that keeps only three pages with useInfiniteFetch maxPages and loads dropped pages again when you scroll back.

Chat historyadvanced

A chat that opens at the newest messages and loads older ones with fetchPreviousPage as you scroll up, keeping your place.

Data tableintermediate

A product table with server-side sorting, search and pagination that keeps the previous rows on screen while the next ones load.

Download progressintermediate

Download a file with a live percentage, speed and time left from onDownloadProgress, then save it from a Blob.

Mutations

Formsbeginner

Submit a form with useSubmit, a typed payload, a submitting state and the validation errors the server sends back.

Optimistic updatesintermediate

Toggle and add todos instantly with setOptimistic, and roll the change back when the server rejects it.

Invalidationbeginner

Invalidate cached lists after a mutation so every useFetch that shows them fetches fresh data.

CRUDintermediate

Create, read, update and delete todos, and write each server response into the cached list instead of refetching it.

File uploadintermediate

Upload a file as FormData with useSubmit, follow each phase of the request with progress bars and cancel it with abort.

Undo deleteadvanced

Delete a todo optimistically, offer Undo for five seconds and send the request only if nobody undoes it, with rollback on failure.

Drag to reorderintermediate

Reorder a list with native drag and drop, update it optimistically and move the item back when the save fails.

Bulk actionsintermediate

Complete or delete many todos at once, one at a time or in parallel, with a progress bar and a result for every row.

Upload progressintermediate

Show a real upload percentage, speed and time left with the Axios adapter, and cancel the upload at any point.

Caching

Stale timeintermediate

See staleTime, cacheTime and the revalidate option at work, with a live view of what is fresh, stale or removed from the cache.

Edit cached data with client.cache.update and watch every component that reads it, through useFetch or useCache, update at once.

Initial databeginner

Show a product's details at once with initialResponse taken from the list, then replace them with the server response.

Shared stateintermediate

Share a cart between distant components through the HyperFetch cache with useCache and client.cache.update, without props or context.

Tab syncintermediate

Send cache changes to every open tab with a BroadcastChannel, so all tabs show the same data without refetching.

Request control

Cancellationintermediate

Cancel in-flight requests with abort() and with cancelable requests that stop the previous search when a new one starts.

Retriesintermediate

Retry failed requests with retry and retryTime, and watch every attempt end in a final success or error.

Deduplicationintermediate

Let many callers that ask for the same data at once share one network request with deduplicate.

Queueadvanced

Send messages one at a time with queued requests, and start, pause, stop or remove them with useQueue.

Authenticationintermediate

Log in, attach the token to every request with onAuth and refresh it on a 401 with onError.

Response mappingintermediate

Validate API responses with zod and map them to the app shape with setResponseMapper.

Mockingbeginner

Build a screen before its backend exists with setMock - mocked data, latency, errors and timeouts.

Custom retryadvanced

Retry only network errors and 5xx answers, with exponential backoff and jitter, and log every attempt.

Retry-Afteradvanced

Handle 429 Too Many Requests in one client interceptor that waits as long as the Retry-After header says and sends the request again.

Timeoutsbeginner

Set a timeout per request with the adapter options, show a clear timeout state, and retry with the same or a longer limit.

Pluginsintermediate

Write a logging plugin and a metrics plugin that see every request of the client, and show their output live.

Payload validationintermediate

Validate the payload with zod in a request mapper, show field errors in the form, and send nothing when the data is invalid.

Typed errorsintermediate

Give each endpoint its own error type on top of the global one, and narrow the union in the UI to show the right message.

Offline and persistence

Persist both the cache (IndexedDB) and the request queue (localStorage), so the app opens with data and keeps changes made offline across reloads.

Offline queueintermediate

Requests made offline wait in the queue and are sent in order when the app is back online.

Cache persistenceintermediate

Persist the cache to localStorage so a reload shows data at once, without a request.

Persist large responses in IndexedDB with the cache lazyStorage, and show them from disk while the API is asked again.

Cache versionsintermediate

Bump the cache version with a release, so persisted data in an old shape is dropped instead of breaking the new code.

Keep offline mutations in a persistent dispatcher queue, so they survive a page reload and are sent once online.

Realtime and streaming

WebSocket chatintermediate

A chat over WebSocket with useListener and useEmitter, connection state and reconnects.

Server-sent eventsintermediate

Listen to a live server-sent events stream with the SSE adapter and useListener, with pause and resume.

Streamingintermediate

Render a streamed HTTP response chunk by chunk with useStream, the way chat apps show an LLM answer.

Live cache updatesintermediate

Load a list once with useFetch and keep its cache current with server-sent events from a local Hono server.

AI chatintermediate

Stream a model answer token by token from a local Hono server with useStream, with stop and regenerate.

Notificationsintermediate

Live notifications pushed over server-sent events from a local Hono server, with an unread badge, mark as read and a capped list.

Adapters and integrations

GraphQLbeginner

Query a GraphQL API with the GraphQL adapter - typed queries, variables and per-variable caching.

Axiosbeginner

Send HyperFetch requests with axios through the Axios adapter, with axios options and errors passed through.

Devtoolsbeginner

Connect a client to the HyperFlow devtools with the devtools plugin and inspect requests, cache and queues.

Honointermediate

A Hono API and a React client in one Vite app, with requests typed from the Hono routes.

tRPCintermediate

A tRPC router served by Hono and a React client that calls it through HyperFetch with types inferred from the router.

A live chat on tRPC subscriptions, streamed over Server-Sent Events into useListener with typed events and resume support.

oRPCintermediate

A contract-first oRPC API on Hono and a React client typed from the contract, with Dates and typed errors kept end to end.

Stream job progress from an oRPC async generator into useListener over an HTTP event stream, with event ids and typed events.

Elysiaintermediate

An Elysia API on Node.js and a React client whose requests, query params and error bodies are typed from the Elysia routes.

OpenAPI codegenintermediate

Generate typed HyperFetch requests from the Swagger Petstore OpenAPI spec with @hyper-fetch/cli and use them in React.

GraphQL mutationsintermediate

Create, update and delete with GraphQL mutations and write each result into the cached query instead of fetching it again.

Firebaseintermediate

A Firestore guestbook where every read and write is a HyperFetch request, with query constraints, typed documents and errors in the response.

A Node.js script that sends typed requests, runs them in parallel and retries failures, with code that also runs in Bun, Deno and Workers.

Frameworks

Next.js App Routerintermediate

Fetch on the server in a Next.js App Router page and hydrate the response into the client cache.

Stream slow server data into a Next.js App Router page section by section with Suspense, and hydrate each section into HyperFetch hooks.

Fetch in getServerSideProps, dehydrate the responses and hydrate them into HyperFetch hooks with one Hydrate in _app.

React Routerintermediate

React Router loaders prefetch through HyperFetch so components read from the cache, and an action saves edits and updates the cache.

TanStack Routerintermediate

TanStack Router loaders fill the HyperFetch cache, and hovering a link prefetches the next page before you click.

Astrointermediate

Fetch on the server in an Astro page and hydrate the response into a React island that uses HyperFetch hooks.

Apps

Explore the Rick and Morty API with React Router: search and pages in the URL, dependent requests, prefetch on hover and a cache reused on every visit.

Kanban boardadvanced

A kanban board with native drag and drop, optimistic moves with rollback, a sync status and changes shared between tabs.

Shopadvanced

A small shop with React Router: catalog with categories, search and infinite scroll, an optimistic cart persisted in localStorage, and a validated checkout.

Dashboardintermediate

An admin dashboard with KPI cards from parallel requests, a polled live number, a server-sorted table, an offline banner and errors kept inside each widget.

TodoMVCintermediate

TodoMVC with a Hono API in the same Vite app: filters in the URL, optimistic toggles and edits, clear completed, and todos stored on the server.