Cache updates
A profile editor with a navigation bar and an email badge. Only the editor fetches the user. The other two read the same
cache entry with useCache, so typing in the editor updates all three at once, and no request is sent.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type User = {
id: number;
firstName: string;
lastName: string;
email: string;
image: string;
};
/** Every component below uses this exact request, so they all read the same cache entry. */
export const getUserRequest = client
.createRequest<{
response: User;
queryParams: { select: string };
}>()({ endpoint: "/users/:userId" })
.setParams({ userId: 1 })
// `select` is a dummyjson query param: the API returns only these fields.
.setQueryParams({ select: "firstName,lastName,email,image" });
/** Writes into the cache. Every hook that reads `getUserRequest` re-renders with the new data, no request is sent. */
export const updateCachedUser = (changes: Partial<User>) => {
client.cache.update(getUserRequest, (cached) => (cached?.data ? { data: { ...cached.data, ...changes } } : {}));
};
npx tiged BetterTyped/hyper-fetch/examples/react/cache-updates hyper-fetch-react-cache-updates && cd hyper-fetch-react-cache-updates && npm install && npm run dev- One cache entry, many readers: hooks that use the same request share its data.
client.cache.update()changes cached data locally, and every reader re-renders.useCachereads the cache without ever sending a request.selectonuseCachepicks one field, so the component re-renders only when that field changes.
How it works
-
getUserRequesthas its params and query params set inapi.ts, so every component uses exactly the same cache key. -
ProfileEditorcallsuseFetch(getUserRequest). It fetches the user and fills the cache. -
NavBarandEmailBadgecalluseCache(getUserRequest). They show nothing until the data is in the cache, then follow every change to it. -
Each input calls
updateCachedUser(), which merges the change into the cached response:client.cache.update(getUserRequest, (cached) =>cached?.data ? { data: { ...cached.data, ...changes } } : {},);cache.update()merges a partial response into the entry,cache.set()replaces it. Both emit a cache event that every hook on that key listens to. -
Reload from server calls
refetch(). The server's data overwrites the local edits.
The setData action returned by useFetch and useCache changes only that hook's own state. Use client.cache when
other components should see the change.
- Writing a mutation response into the cache, so lists and details show it without another request.
- Local edits that several components show at once, such as a profile name in a header and a settings page.
- Read-only widgets (headers, badges, counters) that should show data another component fetched.
Related
Every hook that uses the same request reads the same cache entry. client.cache.update() changes that entry, and
useFetch and useCache hooks everywhere re-render with the new data.
