Live cache updates
An orders table that is fetched once and then stays current. A small Hono server in the same Vite app creates and moves orders every few seconds and pushes each change as a server-sent event. The client writes every event into the cached list, so no refetch is needed. Press Advance in a second tab and watch the first one update.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
export type OrderStatus = "new" | "packing" | "shipped" | "delivered";
export type Order = { id: number; customer: string; total: number; status: OrderStatus; updatedAt: string };
export type OrderEvent = { type: "created" | "updated"; order: Order };
const flow: OrderStatus[] = ["new", "packing", "shipped", "delivered"];
const customers = ["Ada", "Grace", "Linus", "Margaret", "Ken", "Barbara", "Dennis"];
// In memory, so the data resets when the dev server restarts.
let nextId = 4;
const orders: Order[] = [
{ id: 3, customer: "Ada", total: 120, status: "new", updatedAt: new Date().toISOString() },
{ id: 2, customer: "Grace", total: 64, status: "packing", updatedAt: new Date().toISOString() },
{ id: 1, customer: "Linus", total: 245, status: "shipped", updatedAt: new Date().toISOString() },
];
// ---------- Fan-out to every open event stream ----------
const subscribers = new Set<(event: OrderEvent) => void>();
const publish = (event: OrderEvent) => subscribers.forEach((send) => send(event));
const advance = (order: Order) => {
order.status = flow[Math.min(flow.indexOf(order.status) + 1, flow.length - 1)];
order.updatedAt = new Date().toISOString();
publish({ type: "updated", order });
return order;
};
// Other "users" work on the orders too: something changes every few seconds while anyone is watching.
let timer: ReturnType<typeof setInterval> | undefined;
const simulateActivity = () => {
const open = orders.filter((order) => order.status !== "delivered");
if (open.length < 2 || Math.random() < 0.3) {
const customer = customers[Math.floor(Math.random() * customers.length)];
const order: Order = {
id: nextId++,
customer,
total: 20 + Math.round(Math.random() * 300),
status: "new",
updatedAt: new Date().toISOString(),
};
orders.unshift(order);
publish({ type: "created", order });
} else {
advance(open[Math.floor(Math.random() * open.length)]);
}
};
const app = new Hono()
.basePath("/api")
.get("/orders", (c) => c.json(orders.slice(0, 8)))
.post("/orders/:orderId/advance", (c) => {
const order = orders.find((item) => item.id === Number(c.req.param("orderId")));
if (!order) return c.json({ message: "No such order" }, 404);
return c.json(advance(order));
})
// One stream per browser tab. Each change is sent as a named event, `event: order`.
.get("/events", (c) =>
streamSSE(c, async (stream) => {
const send = (event: OrderEvent) => void stream.writeSSE({ event: "order", data: JSON.stringify(event) });
subscribers.add(send);
timer ??= setInterval(simulateActivity, 3000);
stream.onAbort(() => {
subscribers.delete(send);
if (subscribers.size === 0) {
clearInterval(timer);
timer = undefined;
}
});
// Keep the response open. A comment line every 15 s keeps proxies from closing an idle stream.
while (!stream.aborted) {
await stream.sleep(15000);
await stream.write(": ping\n\n");
}
}),
);
// `@hono/vite-dev-server` serves the default export inside the Vite dev server.
export default app;
npx tiged BetterTyped/hyper-fetch/examples/react/live-cache-updates hyper-fetch-react-live-cache-updates && cd hyper-fetch-react-live-cache-updates && npm install && npm run devuseFetchloads the list once and reads it from the cache from then on.ServerSentEventsAdapteropens oneEventSource, anduseListenerreceives itsorderevents.client.cache.update()applies each event to the cached list, so every hook reading it re-renders.- Writes without local updates: the Advance button only sends a
POST. The change comes back as an event.
How it works
-
server/app.tsis a Hono app that@hono/vite-dev-serverruns for every/apirequest.GET /api/ordersreturns the list,POST /api/orders/:orderId/advancemoves an order to the next status, andGET /api/eventskeeps astreamSSEresponse open per tab. -
Every change goes through
publish(), which writes a named event to each open stream:event: orderwith{ type, order }as data. -
api.tscreates an HTTP client and a socket client. WithServerSentEventsAdapter, a named event is delivered to the listener whose topic has the same name:export const onOrderEvent = socket.createListener<OrderEvent>()({ topic: "order" }); -
useLiveOrderscombines both:useFetch(getOrders)for the first load, anduseListener(onOrderEvent).onEvent()for the changes.applyEventreplaces the order with the same id, or puts a new one on top, withclient.cache.update(getOrders, ...). -
The cache update emits a cache event, and
useFetchre-renders with the new list. A newupdatedAtgives the row a new key, so its highlight replays. -
AdvanceButtoncallsuseSubmit(advanceOrder...)and ignores the response. The server publishes the change, and every tab, this one too, applies it through the same path.
The network panel shows one GET /api/orders and one long GET /api/events, however many changes arrive.
- Dashboards, order boards, feeds and admin lists that other people change while you watch.
- Replacing polling: one open stream instead of a request every few seconds.
- Collaborative screens, where your own writes should arrive the same way as everyone else's.
Related
useFetch loads the list, a server-sent events listener receives every change, and client.cache.update() writes the
change into the cached list. The list stays live without refetching.
