Skip to main content

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.

intermediateuseFetchuseListenerrealtimecacheserver
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;
Run locallynpx 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 dev
What it shows
  1. useFetch loads the list once and reads it from the cache from then on.
  2. ServerSentEventsAdapter opens one EventSource, and useListener receives its order events.
  3. client.cache.update() applies each event to the cached list, so every hook reading it re-renders.
  4. Writes without local updates: the Advance button only sends a POST. The change comes back as an event.

How it works​

  1. server/app.ts is a Hono app that @hono/vite-dev-server runs for every /api request. GET /api/orders returns the list, POST /api/orders/:orderId/advance moves an order to the next status, and GET /api/events keeps a streamSSE response open per tab.

  2. Every change goes through publish(), which writes a named event to each open stream: event: order with { type, order } as data.

  3. api.ts creates an HTTP client and a socket client. With ServerSentEventsAdapter, a named event is delivered to the listener whose topic has the same name:

    export const onOrderEvent = socket.createListener<OrderEvent>()({ topic: "order" });
  4. useLiveOrders combines both: useFetch(getOrders) for the first load, and useListener(onOrderEvent).onEvent() for the changes. applyEvent replaces the order with the same id, or puts a new one on top, with client.cache.update(getOrders, ...).

  5. The cache update emits a cache event, and useFetch re-renders with the new list. A new updatedAt gives the row a new key, so its highlight replays.

  6. AdvanceButton calls useSubmit(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.

When to use it
  • 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.

Summary

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.