Optimistic updates
A todo list where checking a box or adding a todo changes the list at once, while the server takes a full second to answer. Turn on Make requests fail and the same change is reverted when the error arrives.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useIsSubmitting, useSubmit } from "@hyper-fetch/react";
import { useState } from "react";
import type { FormEvent } from "react";
import { addTodoRequest, client, getTodosRequest, setFailRequests, toggleTodoRequest } from "./api";
export const App = () => {
const [fail, setFail] = useState(false);
const [log, setLog] = useState<string[]>([]);
const addLog = (line: string) =>
setLog((lines) => [`${new Date().toLocaleTimeString()} ${line}`, ...lines].slice(0, 6));
const { data, error, loading } = useFetch(getTodosRequest);
// Nothing optimistic-specific here: the requests carry their own optimistic changes.
const toggle = useSubmit(toggleTodoRequest);
const add = useSubmit(addTodoRequest);
const saving = useIsSubmitting(client);
toggle.onSubmitSuccess(({ response }) => addLog(`Saved todo #${response.data.id}`));
add.onSubmitSuccess(({ response }) => addLog(`Saved "${response.data.todo}"`));
// By the time these run, core has already reverted the change in the cache.
toggle.onSubmitError(({ response }) => addLog(`Toggle failed (${response.status}), rolled back`));
add.onSubmitError(({ response }) => addLog(`Add failed (${response.status}), rolled back`));
const handleAdd = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
const todo = String(new FormData(form).get("todo") ?? "").trim();
if (!todo) return;
add.submit({ payload: { todo, completed: false, userId: 1 } });
addLog(`Added "${todo}" to the list`);
form.reset();
};
const handleFailChange = (checked: boolean) => {
setFail(checked);
setFailRequests(checked);
};
return (
<main className="container narrow">
<hgroup>
<h1>Todos</h1>
<p>Changes show up at once. The server answers a second later, and a failure puts the old value back.</p>
</hgroup>
<label>
<input
type="checkbox"
role="switch"
checked={fail}
onChange={(event) => handleFailChange(event.target.checked)}
/>
Make requests fail
</label>
<form className="add" onSubmit={handleAdd}>
<input name="todo" placeholder="New todo" aria-label="New todo" />
<button type="submit">Add</button>
</form>
{loading && !data && <p aria-busy="true">Loading todos...</p>}
{error && <p>Could not load todos: {error.message}</p>}
<ul className="todos">
{data?.todos.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.completed}
// Negative ids are temporary rows; dummyjson does not store them, so they cannot be patched.
disabled={todo.id < 0}
onChange={() =>
toggle.submit({
params: { todoId: todo.id },
payload: { completed: !todo.completed },
})
}
/>
{todo.completed ? <s>{todo.todo}</s> : todo.todo}
</label>
</li>
))}
</ul>
<article>
<header className="toolbar">
<strong>Log</strong>
<small aria-busy={saving > 0}>{saving > 0 ? `Waiting for ${saving} response(s)` : "Idle"}</small>
</header>
{log.length === 0 ? (
<p className="muted">Toggle or add a todo.</p>
) : (
<ol className="log">
{log.map((line, index) => (
<li key={index}>{line}</li>
))}
</ol>
)}
</article>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/optimistic-updates hyper-fetch-react-optimistic-updates && cd hyper-fetch-react-optimistic-updates && npm install && npm run devsetOptimisticon the request describes the change, so components only callsubmit().optimistic()helpers:.list("todos").patch()and.insert()edit the cached list without hand-written cache code..rollback()puts the old value back after a final error or an abort.- Mocking on demand:
setMockplussetMockingEnabledsimulate a server error without a special endpoint. useIsSubmittingshows how many mutations are still waiting for the server.
How it works
-
getTodosRequestis the list on screen. The optimistic changes target this exact request, so they edit the same cache entry thatuseFetchreads. -
toggleTodoRequest.setOptimistic()returns the change and its undo.paramsandpayloadcome from thesubmit()call and are typed:optimistic(getTodosRequest).list("todos").patch(params.todoId, payload).rollback(({ data, previous }) => {// Return `data` with the todo from `previous` put back});The change is applied inside
submit(), before the request is sent, so the checkbox flips in the same render. -
addTodoRequestinserts a temporary todo with a negative id at the top of the list. Its rollback removes that todo again. -
On a final error, core runs every rollback and then calls
onSubmitError. The component only writes a log line. -
Both mutations return
revalidate: false. By default core refetches the changed list once the mutation settles, to get the server's truth. dummyjson only simulates writes, so that refetch would undo every successful change. With a real API, leaverevalidateon. -
api.tsattaches a mock that answers500after one second, then disables it. The switch callssetMockingEnabled(fail)on both requests, and everysubmit()after that uses the mock instead of the network.
- Toggles, likes, reordering and other small changes that almost always succeed.
- Lists where the user expects to see the new item right away.
- Avoid it when the server decides the result, for example prices or generated numbers. Use a pessimistic update with a loading state there.
Related
The request owns the optimistic change: optimistic() helpers describe it and .rollback() describes the undo. Core
applies it on submit(), reverts it on failure and keeps the component free of cache code.
