Optimistic updates
Write a change to the cache before the server confirms it, and undo it on failure.
An optimistic update shows the change before the server confirms it. There are two ways to do it: in the component that runs the mutation, or in the cache, where every screen sees it.
The examples import api.ts and todos.ts from Getting started, and entities.ts from Entities.
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
(Invalidate after a mutation):
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 once 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 sees it: another can list the runs in progress with
useMutationState (Show activity).
In the cache. To show the change everywhere the data is cached, write
the cache in optimistic. If the request fails, every write it made is
undone, newest first. This toggleTodo flips the todo at once, in its own
query and in every cached list, through the Todos entity
(Entities):
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.
: () => .(, ),
: [],
},
);Without an entity, write each query yourself: Query.update(todo({ params }), f)
for the detail and Query.update(todos, f) for every cached list
(Use the cache from Effect).
A written value shows until the next fetch of that query settles, so the old value never flashes back while the refetch runs. Two 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 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.