Cache versions
A profile card with a persisted cache and two "releases". Release 2 also shows the email and avatar. Switch to it without a version bump and it reads the user saved by release 1, which has no email. Turn the bump on and the old entry is dropped and fetched again.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { useEffect, useState } from "react";
import { bumpWithRelease, cacheVersion, client, getUser, readPersisted, release, setDemo } from "./api";
const pageLoadedAt = Date.now();
// Taken before any hook reads the cache, which is when old entries get removed.
const atPageLoad = readPersisted();
const Profile = () => {
// Cache first: a fresh entry from localStorage is used without a request.
const { data, error, loading, responseTimestamp } = useFetch(getUser, { revalidate: false });
if (loading && !data) return <p aria-busy="true">Loading the user from the network...</p>;
if (error) return <p className="error">Could not load the user: {error.message}</p>;
if (!data) return null;
const fromStorage = responseTimestamp !== null && responseTimestamp.getTime() < pageLoadedAt;
return (
<article>
<p>{fromStorage ? <mark>Read from localStorage</mark> : "Fetched from the network"}</p>
<div className="profile">
{release === 2 &&
(data.image ? <img src={data.image} alt="" width={64} height={64} /> : <div className="avatar" />)}
<div>
<strong>
{data.firstName} {data.lastName}
</strong>
{/* Release 2 reads a field that release 1 never saved. */}
{release === 2 && (
<p>{data.email ?? <span className="error">email is missing: this is release 1 data</span>}</p>
)}
</div>
</div>
</article>
);
};
const EntryList = ({ entries }: { entries: ReturnType<typeof readPersisted> }) => (
<ul className="list">
{entries.length === 0 && <li className="muted">Empty</li>}
{entries.map(({ key, version }) => (
<li key={key}>
<code>{key}</code>
{version === cacheVersion ? <small>{version}</small> : <mark>{version}: ignored and removed</mark>}
</li>
))}
</ul>
);
const Persisted = () => {
const [now, setNow] = useState(readPersisted);
useEffect(() => client.cache.events.onData(() => setNow(readPersisted())), []);
return (
<article>
<h6>
Cache version <code>{cacheVersion}</code>
</h6>
<small className="muted">localStorage at page load</small>
<EntryList entries={atPageLoad} />
<small className="muted">localStorage now</small>
<EntryList entries={now} />
</article>
);
};
export const App = () => (
<main className="container">
<hgroup>
<h1>Cache versions</h1>
<p>Load release 1, then deploy release 2. Without a version bump, release 2 reads the old saved shape.</p>
</hgroup>
<div className="toolbar">
<div role="group">
{[1, 2].map((value) => (
<button
key={value}
type="button"
className={value === release ? undefined : "outline secondary"}
onClick={() => setDemo(value, bumpWithRelease)}
>
Release {value}
</button>
))}
</div>
<label>
<input
type="checkbox"
role="switch"
checked={bumpWithRelease}
onChange={(event) => setDemo(release, event.target.checked)}
/>
Bump cache version with the release
</label>
</div>
<div className="grid-2">
<Profile />
<Persisted />
</div>
</main>
);
npx tiged BetterTyped/hyper-fetch/examples/react/cache-versions hyper-fetch-react-cache-versions && cd hyper-fetch-react-cache-versions && npm install && npm run devCache({ version })tags every saved entry with the version it was written under.- Entries from another version are never returned, and are deleted when the cache reads them.
- A version per release keeps old persisted data from reaching code that expects a new shape.
How it works
-
api.tspersists the cache inlocalStorage, as in the cache persistence example, and passes aversion:cache: () => new Cache({ storage: localStorageCache, version: cacheVersion }), -
releaseandbumpWithReleasecome fromlocalStorageonly to simulate a deploy in the browser. In a real app the version is a constant in the code, changed in the same commit as the data shape, or taken from the build. -
getUseruses a fixedcacheKey: "current-user", so both releases share one entry. Release 2 asks for more fields withselect, like an API that returns more fields under the same URL. -
Profilereads it cache first withuseFetch(getUser, { revalidate: false }), so a saved entry is used without a request. That is when an old shape would reach the new code. -
When the cache reads an entry whose
versiondiffers from its own, it returns nothing, deletes the entry, and the hook fetches it again.PersistedshowslocalStorageat page load, before any read, and now.
Entries that are never read again stay in the storage until the garbage collector removes them after their cacheTime,
or until cache.clear() runs.
- Every app with a persisted cache: change the version whenever a cached response changes shape.
- After a fix to a response mapper, so data mapped by the old code is not reused.
- When cached data depends on the user or the locale, as one part of the version.
Related
new Cache({ version }) stamps every saved entry. After a deploy with a new version, entries in the old shape are
ignored and removed when they are read, and the hooks fetch fresh data.
