Skip to main content

Kanban board

A three-column board. Drag a card to another column, add, rename or delete one: the board changes at once and saves in the background. Turn on Make the server fail to see every change undone, and open a second tab to see both tabs stay in sync.

The backend is a mock built with HyperFetch mocking. It keeps the board in localStorage, so the data survives a reload and every tab reads the same cards, like a real database. Swap the client url for your API, delete mock-server.ts, and the rest of the app stays the same.

advancedoptimisticuseSubmitsyncmockingcache
import { type Card, createCard, deleteCard, getCards, updateCard } from "./cards";

/**
* A fake backend built with HyperFetch mocking. `setMock` replaces the adapter of a request, so the app code is the
* same as with a real API. The board is kept in localStorage: it survives a reload and every tab sees the same data,
* like a real database would.
*/
const STORAGE_KEY = "hyper-fetch-kanban";

const seed: Card[] = [
{ id: 1, title: "Write the release notes", status: "todo" },
{ id: 2, title: "Review the pull request", status: "todo" },
{ id: 3, title: "Fix the login redirect", status: "doing" },
{ id: 4, title: "Set up the staging server", status: "done" },
];

const readCards = (): Card[] => {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? JSON.parse(saved) : seed;
};

const writeCards = (cards: Card[]) => localStorage.setItem(STORAGE_KEY, JSON.stringify(cards));

// Slow enough to see the optimistic change before the server answers.
const latency = { responseTime: 700 };

let failing = false;

/** While on, every write answers 500 and HyperFetch rolls the optimistic change back. */
export const setServerFailing = (value: boolean) => {
failing = value;
};

export const resetServer = () => writeCards(seed);

const serverError = () => ({ error: { message: "The server is down" }, status: 500 });
const notFound = () => ({ error: { message: "This card no longer exists" }, status: 404 });
const badRequest = () => ({ error: { message: "Missing card data" }, status: 400 });

getCards.setMock(() => ({ data: readCards(), status: 200 }), latency);

createCard.setMock(({ request }) => {
if (failing) return serverError();
if (!request.payload) return badRequest();
const cards = readCards();
const card: Card = { ...request.payload, id: Math.max(0, ...cards.map((item) => item.id)) + 1 };
writeCards([...cards, card]);
return { data: card, status: 201 };
}, latency);

updateCard.setMock(({ request }) => {
if (failing) return serverError();
const cards = readCards();
const card = cards.find((item) => item.id === Number(request.params?.cardId));
if (!card) return notFound();
const updated = { ...card, ...request.payload };
writeCards(cards.map((item) => (item.id === card.id ? updated : item)));
return { data: updated, status: 200 };
}, latency);

deleteCard.setMock(({ request }) => {
if (failing) return serverError();
const id = Number(request.params?.cardId);
writeCards(readCards().filter((item) => item.id !== id));
return { data: { id }, status: 200 };
}, latency);
Run locallynpx tiged BetterTyped/hyper-fetch/examples/apps/kanban hyper-fetch-apps-kanban && cd hyper-fetch-apps-kanban && npm install && npm run dev
What it shows
  1. Optimistic updates on the request: setOptimistic with insert, patch and remove moves, adds and deletes cards before the server answers (Optimistic updates).
  2. Rollback and commit: a failed write puts the card back where it was, a saved card gets its real id (Undo delete, Drag to reorder).
  3. Queued writes: queued: true sends the writes to one card in order (Queue).
  4. Sync status: useIsSubmitting counts the writes in flight, request events fill the activity log (CRUD).
  5. Tab sync: cache changes travel to the other tabs over a BroadcastChannel (Tab sync).
  6. A mock backend: setMock answers every request, with latency and failures on demand (Mocking).

How it works​

  1. api/cards.ts defines the board request getCards and three writes: createCard, updateCard and deleteCard. The writes carry their optimistic changes, so the components only call submit(). Moving a card and renaming it are the same updateCard request with a different payload.

  2. updateCard patches the card in the cached board and describes its undo. restore() puts the old card back at its old index and keeps every other change made in the meantime:

    optimistic(getCards)
    .patch(params.cardId, payload)
    .rollback(({ data, previous }) => restore(data, previous, Number(params.cardId)));
  3. createCard inserts a card with a temporary negative id. .commit() swaps it for the card from the response, and .rollback() removes it. While the id is negative, CardItem shows the card as busy and disables its buttons.

  4. After the last write to the board settles, core refetches getCards to get the server's truth. The mock stores every write, so that refetch confirms the change.

  5. Column uses the native drag and drop API. onDragStart puts the card id into dataTransfer, and onDrop sends updateCard with the column's status. No drag and drop library is needed.

  6. SyncStatus combines useIsSubmitting(client) with the activity log from api/activity.ts, which listens to client.requestManager.events.onResponse. Every write, from any component, ends up in one place.

  7. api/tab-sync.ts posts every cache write (responses, optimistic changes and rollbacks) to a BroadcastChannel. The other tabs save the same entry with client.cache.set(), and their useFetch re-renders without a request.

  8. api/mock-server.ts attaches a mock to each request with setMock, and answers after 700 ms. The Make the server fail switch makes the writes answer 500.

When to use it
  • Boards, lists and editors where users expect every change to show up at once.
  • Apps that are often open in several tabs, such as dashboards and admin panels.
  • Prototypes: build the frontend against a mock backend first, then switch the client url.

Summary

Each request owns its optimistic change and its undo, so drag and drop, add, rename and delete are one submit() call each. Request events feed the sync status, cache events feed the other tabs, and setMock stands in for the backend.