Tab sync
A todo list that stays the same in every open tab. Open the preview in two browser tabs and put them side by side. Check a todo in one tab and the other one updates at once, with no request of its own.
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 };
export const getTodos = client
.createRequest<{ response: { todos: Todo[] }; queryParams: { limit: number; select: string } }>()({
endpoint: "/todos",
})
// `select` is a dummyjson query param: the API returns only these fields.
.setQueryParams({ limit: 5, select: "todo,completed" });
export const toggleTodo = client.createRequest<{ response: Todo; payload: Pick<Todo, "completed"> }>()({
endpoint: "/todos/:todoId",
method: "PATCH",
// The answer goes into the list below, so it does not need a cache entry (or a message to the other tabs).
cache: false,
});
npx tiged BetterTyped/hyper-fetch/examples/react/tab-sync hyper-fetch-react-tab-sync && cd hyper-fetch-react-tab-sync && npm install && npm run devcache.events.onDatareports every write to the cache: responses,cache.update()andcache.set().BroadcastChannelcarries the cache entry to the other tabs of the same site.cache.set()in the receiving tab stores the entry and re-renders everyuseFetchthat reads it.- A guard flag keeps a received change from being sent back, so tabs never loop.
How it works
-
tab-sync.tsopensnew BroadcastChannel("hyper-fetch-cache"). Every tab that opens the same name receives the messages of the others, but not its own. -
client.cache.events.onDatafires for each cache write in this tab. Entries withcached: trueare posted to the channel as they are: a cache entry is plain data, so it passes the structured clone ofpostMessage. -
The receiving tab calls
client.cache.set(). Its first argument normally is a request, but it only needscacheKey,cache,staleTime,cacheTimeandscope, and the entry has all of them:client.cache.set({ ...data, cache: true }, data); -
cache.set()emitsonDataagain.applyingRemoteChangeistruewhile it runs, so the listener from step 2 does not post the change back. -
In
App.tsx, checking a todo sendsPATCH /todos/:todoIdand writes the answer to the list withclient.cache.update(getTodos, ...). That one write reaches every tab. -
SyncLogreads the messages withuseSyncExternalStore, so you can see what each tab sent and received.
DummyJSON does not store the change. Reloading any tab fetches the original list, and that response is sent to the other tabs too.
- Apps that people keep open in several tabs, like dashboards, mail and admin panels.
- After login, logout or a settings change that every tab has to show.
- Together with a persisted cache, so tabs agree on what they save.
Related
Twenty lines connect the cache to a BroadcastChannel: onData sends each local write, and cache.set() applies the
writes of other tabs. Every useFetch reading that key updates in all tabs.
