Optimistic updates
Write a change to the cache before the server confirms it, and undo it on failure.
A checkbox that waits for the server feels slow. An optimistic update shows the change before the server confirms it, and takes it back if the request fails. You can show it in the component that runs the mutation, or write it to the cache, where every screen shows it. This page shows both, and what a rollback doesn't cover.
The examples import api.ts and todos.ts from
Getting started, and entities.ts from
Entities.
Show the change in the component
While a run is in progress, useMutation's variables hold what it
sends, so the component can show the change itself and leave the cache
alone. Here a new todo shows, faded, until the list has it. The mutation
refetches the lists in onSuccess, so the run is in progress until they
have the todo, as
Wait for the refetch
explains:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query";
import { } from "@monarcode/effetch-query/react";
import { } from "./api.js";
import { , } from "./todos.js";
const = .(
.("POST /todos", {
: .({ : . }),
: ,
}),
// Refetches the lists and waits, so the run settles after they have it.
{ : () => .() },
);
export function ({ }: { readonly : string }) {
const { , , } = ();
return (
<>
{. && !== ? (
< ={{ : 0.5 }}>{..}</>
) : null}
<>
< ="button" ={() => void ({ : { } })}>
Add
</>
</>
</>
);
}If the run fails, the faded todo goes, and there's nothing to undo. Only
this component shows it. Another component can list the runs in progress
with useMutationState, as Show activity
describes.
Write the change to the cache
To show the change everywhere the data is cached, write the cache in the
mutation's optimistic option. If the request fails, every write it made
is undone, newest first. This version of Getting started's toggleTodo
flips the todo at once, in its own query and in every cached list, with
Query.update:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query";
import { } from "./api.js";
import { , , } from "./todos.js";
export const = .(
.("PATCH /todos/:id", {
: .({ : . }),
: ,
}),
{
: ({ : { }, : { } }) =>
.(
// The todo's own query.
.(({ : { : () } }), () => ({
...,
,
})),
// Each cached list, whatever its filter.
.(, () =>
.(() =>
. === () ? { ..., } : ,
),
),
),
// The server's version replaces the guess.
: () => .(({ : { : . } }), ),
: [],
},
);An entity does the same in fewer lines. An entity is a schema with an ID,
such as the Todos entity for Todo, and one write to it reaches every
cached copy of a record, in whichever query holds it, as
Entities explains. Here is the same toggleTodo
with the entity:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query";
import { } from "./api.js";
import { } from "./entities.js";
import { , } from "./todos.js";
export const = .(
.("PATCH /todos/:id", {
: .({ : . }),
: ,
}),
{
// Every cached copy: its own query, and each list, whatever its filter.
: ({ , }) =>
.(, (.), () => ({
...,
: .,
})),
// The server's version replaces the guess.
: () => .(, ),
: [],
},
);Either way, a written value shows until the next fetch of that query
settles, so the old value never flashes back while the refetch runs. Both
versions replace toggle-todo.ts's toggleTodo: define one mutation per
change in your app.
What a rollback doesn't cover
A failed run puts back what its optimistic wrote, with three limits:
- Only writes made while
optimisticruns are undone: not those of a fiber it forks that write after it's done, nor those of a mutation it runs. - A query written again in the meantime is put back all the same, even when a fetch wrote it.
- A fetch of the same query already in progress still settles over the optimistic value, and there's no way to cancel it: the query then shows what that fetch returned.
What's next
- Entities: define the
Todosentity, and write or read a record by its ID. - When runs overlap: what a second click does while the first run is saving.
- The cache: every function that reads and writes the cache.