Skip to main content

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.

beginneruseSubmituseFetchinvalidationcache
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" });
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/invalidation hyper-fetch-react-invalidation && cd hyper-fetch-react-invalidation && npm install && npm run dev
What it shows
  1. client.cache.invalidate() marks cached data stale after a mutation.
  2. Automatic refetch: every mounted useFetch that reads an invalidated key fetches it again right away.
  3. Targeting: pass one request for an exact key, or a RegExp to hit every key that matches, such as all post lists.

How it works​

  1. api.ts defines three lists with their params and query params already set: latest posts, posts of user 1 and users. Their cache keys look like GET_/posts_{"limit":3,...} and GET_/posts/user/1_{...}.

  2. App sends createPostRequest with useSubmit. When it succeeds, onSubmitSuccess invalidates the chosen target:

    onSubmitSuccess(() => {
    client.cache.invalidate(targets[target].keys);
    });
  3. invalidate() accepts a request (its exact cache key), a cache key string, a RegExp or an array of these. The /\/posts/ pattern matches both post lists and leaves users alone.

  4. Invalidation sets the entry's staleTime to 0 and emits an event. Mounted useFetch hooks for that key refetch at once. Components that are not mounted find stale data next time they mount and fetch then.

  5. Panel registers onSuccess to count fetches and shows responseTimestamp, 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.

When to use 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 RegExp covers all of them.
  • With optimistic updates, return invalidate: [request] from setOptimistic to do the same declaratively.

Summary

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.