Skip to main content

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.

intermediateuseSubmitoptimisticcachemocking
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/optimistic-updates hyper-fetch-react-optimistic-updates && cd hyper-fetch-react-optimistic-updates && npm install && npm run dev
What it shows
  1. setOptimistic on the request describes the change, so components only call submit().
  2. optimistic() helpers: .list("todos").patch() and .insert() edit the cached list without hand-written cache code.
  3. .rollback() puts the old value back after a final error or an abort.
  4. Mocking on demand: setMock plus setMockingEnabled simulate a server error without a special endpoint.
  5. useIsSubmitting shows how many mutations are still waiting for the server.

How it works​

  1. getTodosRequest is the list on screen. The optimistic changes target this exact request, so they edit the same cache entry that useFetch reads.

  2. toggleTodoRequest.setOptimistic() returns the change and its undo. params and payload come from the submit() 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.

  3. addTodoRequest inserts a temporary todo with a negative id at the top of the list. Its rollback removes that todo again.

  4. On a final error, core runs every rollback and then calls onSubmitError. The component only writes a log line.

  5. 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, leave revalidate on.

  6. api.ts attaches a mock that answers 500 after one second, then disables it. The switch calls setMockingEnabled(fail) on both requests, and every submit() after that uses the mock instead of the network.

When to use it
  • 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.

Summary

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.