Cache playground
A playground for the cache options. Move a slider, open another post or leave the tab, and a live cache table and event log show what HyperFetch stores, when it sends a request and when it removes data.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useEffect, useState } from "react";
import { client } from "./api";
const seconds = (ms: number) => `${Math.max(Math.ceil(ms / 1000), 0)}s`;
/** Reads every entry of `client.cache` twice a second and shows how long it stays fresh and when it is removed. */
export const CacheTable = () => {
const [now, setNow] = useState(Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 500);
return () => clearInterval(timer);
}, []);
const entries = client.cache
.keys()
.map((key) => client.cache.get(key))
.filter((entry) => entry !== undefined);
return (
<article>
<header>
<strong>Cache</strong>
</header>
{entries.length === 0 ? (
<p className="muted">The cache is empty.</p>
) : (
<table>
<thead>
<tr>
<th>Key</th>
<th>State</th>
<th>Removed in</th>
</tr>
</thead>
<tbody>
{entries.map((entry) => {
// Every entry keeps the times of the request that saved it.
const age = now - entry.responseTimestamp;
const freshFor = entry.staleTime - age;
return (
<tr key={entry.cacheKey}>
<td>
<code>{entry.cacheKey}</code>
</td>
<td>{freshFor > 0 ? <mark>fresh {seconds(freshFor)}</mark> : "stale"}</td>
<td>{seconds(entry.cacheTime - age)}</td>
</tr>
);
})}
</tbody>
</table>
)}
</article>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/cache-playground hyper-fetch-react-cache-playground && cd hyper-fetch-react-cache-playground && npm install && npm run devstaleTimedecides how long a cached response counts as fresh, so opening it again sends no request.cacheTimedecides when the cache removes a response, whether a component uses it or not.retrysends a failed request again, one second apart, before the hook reports the error.refetchOnFocusandrevalidatedecide whenuseFetchasks the server again although it has data.- Client events (
client.cache.eventsandclient.requestManager.events) make the cache and the network visible.
How it works
-
api.tsdefines one request,getPostRequest.getPostWithSettings()builds the request for a post from the current slider values. Request setters return a new request, and the cache key stays the same:getPostRequest.setParams({ postId }).setStaleTime(settings.staleTime * Time.SEC).setCacheTime(settings.cacheTime * Time.SEC).setRetry(settings.retry); -
PostViewpasses that request touseFetchwithrevalidateandrefetchOnFocusfrom the switches. Withrevalidateoff, a post is fetched on mount only when the cache has no fresh copy.bounce: truewaits until you stop dragging a slider before the changed request is sent. -
CacheTablereadsclient.cache.keys()andclient.cache.get()twice a second. Every entry keeps thestaleTimeandcacheTimeof the request that saved it, so new slider values show up after the next response. -
EventLogsubscribes torequestManager.events.onRequestStartandonResponsefor the network, and tocache.events.onData,onInvalidateandonDeletefor the cache.details.willRetrytells a failed attempt that will be retried from the final error. -
Invalidate calls
client.cache.invalidate(request). The entry becomes stale and the mounted hook fetches it again. -
Make requests fail turns on a mock that answers
500. Setretryto 2 and press Refetch to see three attempts. A failed response is not stored, so the post you already have stays on screen.
Things to try:
- Set
staleTimeto 30s, open Post 2 and go back to Post 1. No request is sent until the 30 seconds pass. - Pick None and set a short
cacheTimefirst. The entry disappears from the table when its time runs out. With a post open, a removed entry is fetched again right away. - Turn on
refetchOnFocus, switch to another tab and come back.
- Learning what each cache option does before you set it in your app.
- Picking values: a long
staleTimefor data that rarely changes, a short one for data that changes often.
Related
staleTime controls when data is fetched again, cacheTime controls when it is removed, and retry controls how hard
a request tries. The client's cache and request events show each decision as it happens.
