Offline first
A todo app that works through a whole offline session. It opens with the last list it saw, accepts new todos without a network, and still has both after a reload. When the network comes back, the waiting todos go to the server in order.
HyperFetch persists two things here, each with a storage option on the client module that owns it:
| What | Module | Storage | Why there |
|---|---|---|---|
| Responses | Cache | IndexedDB | Structured data, much more room than localStorage. |
| Changes not sent | submitDispatcher queue | localStorage | The dispatcher reads its storage synchronously. |
| Demo network state | AppManager.initiallyOnline | localStorage | Only so a reload while "offline" stays offline in the demo. |
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useAppManager, useFetch, useQueue } from "@hyper-fetch/react";
import type { FormEvent } from "react";
import { addTodo, client, getTodos, setNetwork } from "./api";
import { CachePanel, QueuePanel } from "./Panels";
const Todos = () => {
// Cache first: fresh persisted data is used as is, with no request on mount.
const { data, error, loading } = useFetch(getTodos, { revalidate: false });
// Todos that wait in the queue are shown right away, marked as pending. They come back after a reload too.
const { requests } = useQueue(addTodo);
if (!data && loading)
return <p aria-busy="true">Loading todos (waits for the network on a first offline visit)...</p>;
if (!data && error) return <p className="error">Could not load todos: {error.message}</p>;
return (
<ul className="list">
{data?.todos.map((todo, index) => (
<li key={`${todo.id}-${index}`}>
<label>
<input type="checkbox" checked={todo.completed} readOnly /> {todo.todo}
</label>
</li>
))}
{requests.map(({ requestId, request }) => (
<li key={requestId} className="pending">
<label>
<input type="checkbox" checked={false} readOnly /> {request.payload?.todo}
</label>
<mark>pending</mark>
</li>
))}
</ul>
);
};
export const App = () => {
const { isOnline } = useAppManager(client);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
const todo = String(new FormData(form).get("todo"));
form.reset();
// No await: the answer can arrive in a later session. The listener in api.ts handles it.
addTodo.send({ payload: { todo, completed: false, userId: 1 } });
};
const clearAll = async () => {
await client.cache.clear();
client.submitDispatcher.clear();
window.location.reload();
};
return (
<main className="container">
<hgroup>
<h1>Offline first</h1>
<p>
Load the list, go offline, add todos and reload. The list and your changes are still here, and sync once
online.
</p>
</hgroup>
<div className="toolbar">
<label>
<input
type="checkbox"
role="switch"
checked={isOnline}
onChange={(event) => setNetwork(event.target.checked)}
/>
{isOnline ? "Online" : "Offline"}
</label>
<div role="group">
<button type="button" className="secondary" onClick={() => window.location.reload()}>
Reload page
</button>
<button type="button" className="outline" onClick={clearAll}>
Clear saved data
</button>
</div>
</div>
<div className="grid-2">
<article>
<h6>Todos</h6>
<form onSubmit={handleSubmit} role="group">
<input name="todo" placeholder="What needs doing?" required />
<button type="submit">Add</button>
</form>
<Todos />
</article>
<div>
<CachePanel />
<QueuePanel />
</div>
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/offline-first hyper-fetch-react-offline-first && cd hyper-fetch-react-offline-first && npm install && npm run devCache({ storage, lazyStorage })keeps responses in memory and writes every change to IndexedDB.Dispatcher({ storage })keeps the queue of unsent mutations inlocalStorage.- Cache first reads with
staleTimeandrevalidate: false: a reload shows the list with no request. - Pending items from the queue show new todos at once, and they are still there after a reload.
- A client-wide response listener applies answers to requests that were restored after a reload.
How it works
-
storage.tsdefines two storages.indexedDbCacheimplementsCacheAsyncStorageTypewithidb-keyval.localStorageQueueimplementsDispatcherStorageTypeon top oflocalStorage. -
api.tsreads IndexedDB once with a top-levelawait, before the first render, and passes the entries as the in-memorystorageof the cache. IndexedDB goes inlazyStorage, so everysetanddeleteis written there too:const persistedCache = await readPersistedCache();cache: () => new Cache({ storage: new Map(persistedCache), lazyStorage: indexedDbCache }),Without the first read,
useFetchwould mount with an empty memory cache and send a request while IndexedDB is still being read. -
getTodossetsstaleTime: Time.DAYandcacheTime: Time.WEEK.TodoscallsuseFetch(getTodos, { revalidate: false }), so fresh saved data is shown as it is. On a first visit without a network, the request waits in the fetch dispatcher and the list shows a loading state. -
addTodohasoffline: trueandqueued: true. The submit dispatcher saves eachsend()inlocalStorageas request JSON (request.toJSON()) and rebuilds it withclient.fromJSON()after a reload. -
TodosreadsuseQueue(addTodo)and renders every waiting request as a pending row. This is the optimistic UI: it comes from the persisted queue, so it survives a reload. Callbacks such assetOptimisticlive in code and are not saved with the request. -
client.requestManager.events.onResponseruns for every response, also for requests restored from storage, where nosend()call waits anymore. It adds the saved todo to the cached list withclient.cache.update(), which writes it to IndexedDB. -
Going online emits the
AppManageronline event and the dispatcher sends the queue. A session that starts online has no such event, soapi.tscallsclient.submitDispatcher.flush()once. -
Clear saved data calls
client.cache.clear()(memory and IndexedDB) andclient.submitDispatcher.clear().
DummyJSON does not store new todos. The app keeps the server answers in the cached list and does not refetch it, because a refetch would bring back the list without them.
- The dispatcher storage is synchronous, so the queue can't live in IndexedDB.
localStorageholds a few megabytes and only JSON, which is enough for a list of pending mutations but not for files. - Reading all of IndexedDB at start suits a cache of tens or hundreds of entries. For large caches use
lazyStoragealone, as in IndexedDB persistence. - A request that is already being sent when the page unloads is aborted by the browser and leaves the queue. Only the requests that were still waiting are kept.
- Every tab reads the same queue. Two open tabs can send a waiting request twice, so give mutations an idempotency key on the server.
- Field, travel and warehouse apps that must open and accept input without a connection.
- Mobile web and React Native apps on unstable networks.
- Any app where "your change was lost" is worse than "your change is waiting".
Related
The cache saves responses to IndexedDB through lazyStorage, and the submit dispatcher saves unsent mutations to
localStorage through its storage. Together they let the app start with data, take changes offline, and send them
when the network returns, across reloads.
