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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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);
npx tiged BetterTyped/hyper-fetch/examples/apps/kanban hyper-fetch-apps-kanban && cd hyper-fetch-apps-kanban && npm install && npm run dev- Optimistic updates on the request:
setOptimisticwithinsert,patchandremovemoves, adds and deletes cards before the server answers (Optimistic updates). - 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).
- Queued writes:
queued: truesends the writes to one card in order (Queue). - Sync status:
useIsSubmittingcounts the writes in flight, request events fill the activity log (CRUD). - Tab sync: cache changes travel to the other tabs over a
BroadcastChannel(Tab sync). - A mock backend:
setMockanswers every request, with latency and failures on demand (Mocking).
How it works
-
api/cards.tsdefines the board requestgetCardsand three writes:createCard,updateCardanddeleteCard. The writes carry their optimistic changes, so the components only callsubmit(). Moving a card and renaming it are the sameupdateCardrequest with a different payload. -
updateCardpatches 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))); -
createCardinserts 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,CardItemshows the card as busy and disables its buttons. -
After the last write to the board settles, core refetches
getCardsto get the server's truth. The mock stores every write, so that refetch confirms the change. -
Columnuses the native drag and drop API.onDragStartputs the card id intodataTransfer, andonDropsendsupdateCardwith the column's status. No drag and drop library is needed. -
SyncStatuscombinesuseIsSubmitting(client)with the activity log fromapi/activity.ts, which listens toclient.requestManager.events.onResponse. Every write, from any component, ends up in one place. -
api/tab-sync.tsposts every cache write (responses, optimistic changes and rollbacks) to aBroadcastChannel. The other tabs save the same entry withclient.cache.set(), and theiruseFetchre-renders without a request. -
api/mock-server.tsattaches a mock to each request withsetMock, and answers after 700 ms. The Make the server fail switch makes the writes answer500.
- 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.
Related
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.
