CRUD
A todo list with all four operations: add a todo, edit its text, check it off and delete it. Each mutation waits for the server, then writes the server's answer into the cached list.
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 Todo = {
id: number;
todo: string;
completed: boolean;
userId: number;
};
type ApiError = { message: string };
// Read
export const getTodosRequest = client
.createRequest<{
response: { todos: Todo[]; total: number };
queryParams: { limit: number };
}>()({
endpoint: "/todos",
})
.setQueryParams({ limit: 5 });
// Create
export const createTodoRequest = client.createRequest<{
response: Todo;
payload: Omit<Todo, "id">;
error: ApiError;
}>()({ endpoint: "/todos/add", method: "POST" });
// Update
export const updateTodoRequest = client.createRequest<{
response: Todo;
payload: Partial<Pick<Todo, "todo" | "completed">>;
error: ApiError;
}>()({ endpoint: "/todos/:todoId", method: "PATCH" });
// Delete
export const deleteTodoRequest = client.createRequest<{
response: Todo & { isDeleted: boolean };
error: ApiError;
}>()({ endpoint: "/todos/:todoId", method: "DELETE" });
/**
* Writes the result of a mutation into the cached list. Every component that reads `getTodosRequest` re-renders
* with the new list, and no extra request is sent.
*/
export const updateCachedTodos = (update: (todos: Todo[]) => Todo[]) => {
client.cache.update(getTodosRequest, (cached) => {
if (!cached?.data) return {};
return { data: { ...cached.data, todos: update(cached.data.todos) } };
});
};
npx tiged BetterTyped/hyper-fetch/examples/react/crud hyper-fetch-react-crud && cd hyper-fetch-react-crud && npm install && npm run dev- Four typed requests:
GET,POST,PATCHandDELETE, with:todoIdparams and typed payloads. - One
useSubmitper row, so each row has its ownsubmittinganderrorstate. - Manual cache updates:
client.cache.update()writes the result into the list, and every reader re-renders. - No extra round trip: the list is never refetched after a change.
How it works
-
api.tsdefinesgetTodosRequestplus one request per operation.updateTodoRequestanddeleteTodoRequestshare the endpoint/todos/:todoId, sosetParams({ todoId })is required before they can be sent. -
updateCachedTodos()wrapsclient.cache.update(). It receives the cached value, changes thetodosarray and writes it back under the same cache key:client.cache.update(getTodosRequest, (cached) => {if (!cached?.data) return {};return { data: { ...cached.data, todos: update(cached.data.todos) } };}); -
TodoItemcallsuseSubmit(updateTodoRequest.setParams({ todoId: todo.id })). On success it swaps the item forresponse.data, the version the server returned. -
Delete removes the item from the cached list; create puts
response.dataat the top. -
The
useFetch(getTodosRequest)inApplistens to its cache key, so it re-renders after everycache.update().
Why update the cache instead of refetching
dummyjson only simulates writes: it answers as if the change was saved, but a new GET /todos returns the original
list. Refetching after each mutation would wipe out your changes, so this example keeps the list in the cache.
The same pattern pays off with real APIs. The mutation response already holds the new item, so writing it into the cache saves a request and updates the screen as soon as the server confirms. Use invalidation instead when one change affects data you cannot compute on the client, such as totals, sorting or other users' edits.
dummyjson also gives every new todo the id 255 and does not know it afterwards. That is why the create handler
replaces an item with the same id, and why editing or deleting a new todo shows a 404 from the server.
- Lists and tables where the mutation response contains the changed item.
- Screens that should update right after the server confirms, without a loading flash from a refetch.
Related
Each operation is a typed request sent with useSubmit. When it succeeds, client.cache.update() writes the result
into the cached list, so every component shows it without another request.
