Resume after reload
A todo form whose offline queue lives in localStorage. Todos added offline are still waiting after you reload the page
or close the tab, and they reach the server once the app is online again.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useAppManager, useQueue } from "@hyper-fetch/react";
import { type FormEvent, useEffect, useState } from "react";
import { addTodo, client, setNetwork, type Todo } from "./api";
type Sent = Todo & { key: number; sentAt: string };
let sentCount = 0;
const Queue = () => {
const { isOnline } = useAppManager(client);
// Starts with the requests restored from localStorage, then follows every change of the queue.
const { requests } = useQueue(addTodo);
return (
<article>
<h6>Persisted queue ({requests.length})</h6>
{requests.length === 0 && <p className="muted">Empty. Nothing is waiting to be sent.</p>}
<ol className="list">
{requests.map((item, index) => (
<li key={item.requestId}>
<span>{item.request.payload?.todo}</span>
{!isOnline && <mark>waiting for network</mark>}
{/* `queued: true` sends one request at a time, the others wait for their turn. */}
{isOnline &&
(index === 0 ? <small aria-busy="true">sending</small> : <small className="muted">next</small>)}
</li>
))}
</ol>
</article>
);
};
/** Listens to every response on the client, so it also catches requests restored after a reload. */
const useSentTodos = () => {
const [sent, setSent] = useState<Sent[]>([]);
useEffect(() => {
return client.requestManager.events.onResponse<typeof addTodo>(({ request, response }) => {
if (request.queryKey !== addTodo.queryKey || !response.data) return;
const todo = { ...response.data, key: ++sentCount, sentAt: new Date().toLocaleTimeString() };
setSent((prev) => [todo, ...prev]);
});
}, []);
return sent;
};
export const App = () => {
const { isOnline } = useAppManager(client);
const sent = useSentTodos();
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
const todo = String(new FormData(form).get("todo"));
form.reset();
// No await: the response may arrive in another page load. The listener above shows it.
addTodo.send({ payload: { todo, completed: false, userId: 1 } });
};
return (
<main className="container">
<hgroup>
<h1>Resume after reload</h1>
<p>
Go offline, add a few todos and reload the page. They are still in the queue, and go out once you are online.
</p>
</hgroup>
<div className="toolbar">
<label>
<input
type="checkbox"
role="switch"
checked={isOnline}
onChange={(event) => setNetwork(event.target.checked)}
/>
{isOnline ? "Online" : "Offline"}
</label>
<button type="button" className="secondary" onClick={() => window.location.reload()}>
Reload page
</button>
</div>
<form onSubmit={handleSubmit} role="group">
<input name="todo" placeholder="What needs doing?" required />
<button type="submit">Add</button>
</form>
<div className="grid-2">
<Queue />
<article>
<h6>Sent in this page load ({sent.length})</h6>
{sent.length === 0 && <p className="muted">No responses yet.</p>}
<ol className="list">
{sent.map((todo) => (
<li key={todo.key}>
<span>{todo.todo}</span>
<small className="muted">{todo.sentAt}</small>
</li>
))}
</ol>
</article>
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/resume-after-reload hyper-fetch-react-resume-after-reload && cd hyper-fetch-react-resume-after-reload && npm install && npm run devDispatcher({ storage })keeps the queue of the submit dispatcher inlocalStorageinstead of memory.toJSONandfromJSONturn a request into plain JSON for the storage and back into a request after a reload.offline: truekeeps the todos in the queue while the app is offline.dispatcher.flush()sends what the last session left behind when the app starts online.
How it works
-
api.tsimplementsDispatcherStorageType(get,set,keys,entries,delete,clear) on top oflocalStorage, with a key prefix so it only touches its own entries. The storage must be synchronous, because the dispatcher reads the queue on every change. -
The client gets it through the
submitDispatcheroption.useSubmitandsend()on aPOSTrequest use that dispatcher:submitDispatcher: () => new Dispatcher({ storage: localStorageQueue }), -
setcallsJSON.stringify, which callsrequest.toJSON()for every queued request. The saved JSON holds the endpoint, method, payload, query params and options, not the class. -
After a reload,
getQueue()reads the JSON and rebuilds each request withclient.fromJSON(), souseQueue(addTodo)lists the restored todos on the first render. -
The dispatcher sends waiting requests when the
AppManageremits the online event. If the app starts online, there is no such event, soapi.tscallsclient.submitDispatcher.flush()once after creating the client. -
The original
send()promise does not survive a reload.useSentTodoslistens toclient.requestManager.events.onResponse, which also fires for the restored requests. -
The Online switch calls
client.appManager.setOnline()and saves its state, andinitiallyOnlinereads it back, so a reload while "offline" stays offline. In a real app, the browser'sonlineandofflineevents drive it.
- A request that is already being sent when the page unloads is aborted by the browser and removed from the queue. The server may or may not have received it. Only the requests that were still waiting are kept.
- Every open tab reads the same
localStoragequeue. Two tabs can send the same request twice. Use a server-side idempotency key, or keep the persistent queue in one tab. - Only JSON values survive. Files and
FormDatapayloads need to be converted first.
- Forms and actions that must not be lost when the user closes the app without a connection.
- React Native and desktop apps, where only one instance of the app runs.
Related
A six-method storage passed to new Dispatcher({ storage }) saves the queue as request JSON. After a reload the
dispatcher rebuilds the requests with fromJSON() and sends them when the app is online.
