Skip to main content

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.

advancedofflinepersistenceuseQueue
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>
);
};
Run locallynpx 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 dev
What it shows
  1. Dispatcher({ storage }) keeps the queue of the submit dispatcher in localStorage instead of memory.
  2. toJSON and fromJSON turn a request into plain JSON for the storage and back into a request after a reload.
  3. offline: true keeps the todos in the queue while the app is offline.
  4. dispatcher.flush() sends what the last session left behind when the app starts online.

How it works​

  1. api.ts implements DispatcherStorageType (get, set, keys, entries, delete, clear) on top of localStorage, 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.

  2. The client gets it through the submitDispatcher option. useSubmit and send() on a POST request use that dispatcher:

    submitDispatcher: () => new Dispatcher({ storage: localStorageQueue }),
  3. set calls JSON.stringify, which calls request.toJSON() for every queued request. The saved JSON holds the endpoint, method, payload, query params and options, not the class.

  4. After a reload, getQueue() reads the JSON and rebuilds each request with client.fromJSON(), so useQueue(addTodo) lists the restored todos on the first render.

  5. The dispatcher sends waiting requests when the AppManager emits the online event. If the app starts online, there is no such event, so api.ts calls client.submitDispatcher.flush() once after creating the client.

  6. The original send() promise does not survive a reload. useSentTodos listens to client.requestManager.events.onResponse, which also fires for the restored requests.

  7. The Online switch calls client.appManager.setOnline() and saves its state, and initiallyOnline reads it back, so a reload while "offline" stays offline. In a real app, the browser's online and offline events drive it.

Limits
  • 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 localStorage queue. 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 FormData payloads need to be converted first.
When to use it
  • 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.

Summary

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.