Shows a change the moment it is made, undoes it and says why if the server refuses it, and tells the page what is still pending. base is the server's state, which the app fetches and stores; a change stays applied over it until its commit settles, so update base before commit resolves. A refused change is taken out and the rest stay, so a slow commit never blocks the next press, and quick changes to one item settle in the order they were made. commit is a plain function that returns a promise, so any data layer fits.
import { useOptimisticAction } from "@/lib/ouro/use-optimistic-action";Example
const { value, pending, reason, run } = useOptimisticAction(liked);
<Button pressed={value} data-ouro-pending={pending ? "" : undefined} onClick={() => run((on) => !on, () => api.like(id))}>Like</Button>Use instead when
- Use
ReactionBar'soptimisticprop instead when the change is a reaction. - Use React's
useOptimisticinstead when the app needs no reason and no pending state to read.
Parameters
base- Type:
T options- Type:
OptimisticActionOptions {}
Returns
OptimisticAction<T>
Types
OptimisticAction
What useOptimisticAction returns.
interface OptimisticAction<T> {
/** The state to draw: `base` with the changes that are still waiting for their answers applied, oldest first. */
value: T;
/** Whether any change is waiting for its answer. */
pending: boolean;
/** Why the latest refused change was undone, in words for the person; `undefined` until one is refused, and again after the next change. */
reason: string | undefined;
/**
* Shows `apply` at once and runs `commit`; resolves `true` when `commit` settles, or `false` when it
* rejects, after the change is undone and `reason` is set. Never rejects.
*/
run: (apply: (current: T) => T, commit: () => Promise<unknown>) => Promise<boolean>;
}OptimisticActionOptions
Options for useOptimisticAction.
interface OptimisticActionOptions {
/** Turns a refusal into the words the person reads. @default the error's `message`, else "That didn't go through" */
describe?: ((error: unknown) => string) | undefined;
}
