Rick and Morty explorer
An explorer for the public Rick and Morty API with two routes: a searchable, paged list of characters and a page for each character with the episodes they appear in. Hover a character before you open it, then go back: the network log on the right shows that neither step sent a request.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { client } from "./client";
export type NetworkLogEntry = { id: number; endpoint: string; time: string };
let entries: NetworkLogEntry[] = [];
const listeners = new Set<() => void>();
// Only requests that reach the network start here. Data read from the cache never shows up in the log.
client.requestManager.events.onRequestStart(({ request }) => {
const query = Object.entries(request.queryParams ?? {}).map(([key, value]) => `${key}=${value}`);
const endpoint = query.length ? `${request.endpoint}?${query.join("&")}` : request.endpoint;
const entry = { id: Date.now() + Math.random(), endpoint, time: new Date().toLocaleTimeString() };
entries = [entry, ...entries].slice(0, 8);
listeners.forEach((listener) => listener());
});
/** A tiny store for `useSyncExternalStore`. */
export const networkLog = {
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
get: () => entries,
};
npx tiged BetterTyped/hyper-fetch/examples/apps/rick-and-morty hyper-fetch-apps-rick-and-morty && cd hyper-fetch-apps-rick-and-morty && npm install && npm run dev- Search and page in the URL:
useSearchParamsholds the state and every page has its own cache key (Filters in the URL, Pagination). - Debounced search:
bouncesends one request when typing stops (Search as you type). - Prefetch on hover:
send({ cachePolicy: "cache-first" })fills the cache for the character, its episodes and the next page (Prefetching). - Dependent requests: the episode ids come from the character response (Dependent requests).
- Cache reused on navigation:
staleTimeplusrevalidate: falserender a visited route without a request (Stale time, React Router). - Deduplication: hovering a link again while its prefetch runs shares that call (Deduplication).
How it works
-
The app is split by feature.
src/api/holds the client, the requests and the network log,src/features/characters/the two routes, andsrc/components/small presentational parts.App.tsxonly declares the routes withcreateBrowserRouter. -
api/characters.tskeeps the raw requests private and exports factories:characterList(page, name),characterDetails(id)andcharacterEpisodes(character). The list, the details page and the prefetch build requests with the same functions, so they always hit the same cache keys. -
Every request has
staleTime: 10 * Time.MIN. The components passrevalidate: falsetouseFetch, which renders fresh cached data without a request and fetches only what is missing or stale:const { data, error, status } = useFetch(characterList(page, name), {revalidate: false,bounce: true,bounceTime: 400,}); -
CharacterListreadsnameandpagefrom the URL. Typing replaces the URL entry, andbouncewaits 400 ms before the request. Only the query params change, so the previous page stays on screen while the next one loads. -
The API answers a search without results with
404and{ error }. The request types that body witherror: ApiError, and the list shows "No characters match" for that status instead of an error. -
Hovering or focusing a character calls
prefetchCharacter(id). It sends the character withcachePolicy: "cache-first", then the episodes from its answer. When you click,CharacterPageandEpisodesfind both in the cache and render at once. The Previous and Next buttons prefetch their page the same way. -
Episodesis the dependent request. It mounts only when the character is loaded and builds the endpoint from the character's episode urls. The API returns an array for/episode/[1,2], also for a single id, so the response type staysEpisode[]. -
api/network-log.tssubscribes toclient.requestManager.events.onRequestStart. That event fires only for requests that reach the network, so cache hits never show up in the log.
- Catalogs and explorers with a list, filters and a details page.
- Apps where users jump back and forth between routes and expect instant pages.
- APIs whose data changes rarely, where a long
staleTimesaves most requests.
Related
Request factories give every screen and every prefetch the same cache keys. With staleTime and revalidate: false the
cache answers repeat visits, cache-first prefetches fill it before a click, and the URL keeps the search and the page.
