Invalidation
A form that creates a post and three lists below it. After the post is created, the app invalidates the cache keys you pick, and the matching lists fetch again. Each list counts its fetches, so you can see which ones reacted.
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" });
type Post = { id: number; title: string };
type User = { id: number; firstName: string; lastName: string };
type ListQuery = { limit: number; select: string };
export const getPostsRequest = client
.createRequest<{
response: { posts: Post[] };
queryParams: ListQuery & { sortBy: "id"; order: "desc" };
}>()({
endpoint: "/posts",
})
// `select` is a dummyjson query param: the API returns only these fields.
.setQueryParams({ limit: 3, select: "title", sortBy: "id", order: "desc" });
export const getUserPostsRequest = client
.createRequest<{
response: { posts: Post[] };
queryParams: ListQuery;
}>()({ endpoint: "/posts/user/:userId" })
.setParams({ userId: 1 })
.setQueryParams({ limit: 3, select: "title" });
export const getUsersRequest = client
.createRequest<{
response: { users: User[] };
queryParams: ListQuery;
}>()({ endpoint: "/users" })
.setQueryParams({ limit: 3, select: "firstName,lastName" });
export const createPostRequest = client.createRequest<{
response: Post;
payload: { title: string; userId: number };
}>()({ endpoint: "/posts/add", method: "POST" });
npx tiged BetterTyped/hyper-fetch/examples/react/invalidation hyper-fetch-react-invalidation && cd hyper-fetch-react-invalidation && npm install && npm run devclient.cache.invalidate()marks cached data stale after a mutation.- Automatic refetch: every mounted
useFetchthat reads an invalidated key fetches it again right away. - Targeting: pass one request for an exact key, or a
RegExpto hit every key that matches, such as all post lists.
How it works
-
api.tsdefines three lists with their params and query params already set: latest posts, posts of user 1 and users. Their cache keys look likeGET_/posts_{"limit":3,...}andGET_/posts/user/1_{...}. -
AppsendscreatePostRequestwithuseSubmit. When it succeeds,onSubmitSuccessinvalidates the chosen target:onSubmitSuccess(() => {client.cache.invalidate(targets[target].keys);}); -
invalidate()accepts a request (its exact cache key), a cache key string, aRegExpor an array of these. The/\/posts/pattern matches both post lists and leaves users alone. -
Invalidation sets the entry's
staleTimeto0and emits an event. MounteduseFetchhooks for that key refetch at once. Components that are not mounted find stale data next time they mount and fetch then. -
PanelregistersonSuccessto count fetches and showsresponseTimestamp, which makes each refetch visible.
dummyjson does not store the new post, so the refetched lists contain the same posts. With a real API, they would include it.
- After a create, update or delete, when you would rather refetch than edit the cached data by hand.
- When one change affects many lists, filters or pages: one
RegExpcovers all of them. - With optimistic updates, return
invalidate: [request]fromsetOptimisticto do the same declaratively.
Related
After a mutation, client.cache.invalidate() marks the affected keys stale, and every useFetch showing them fetches
fresh data. A request targets one key, a RegExp targets a whole group.
