Run a mutation
Run a mutation from a component or from Effect, and choose what happens when runs overlap.
A user clicks a checkbox, and the todo should be saved. useMutation
runs a mutation from a component and gives that component its own state
for it: whether it's saving, and whether it failed. This page shows how to
run one, react to one run's result, choose what a second click does while
the first is saving, and run a mutation from Effect.
The examples import api.ts, client.ts, todos.ts and toggle-todo.ts
from Getting started.
Run from a component
This checkbox toggles a todo, and clears a failure after three seconds:
import * as from "effect/Exit";
import { } from "@monarcode/effetch-query/react";
import type { } from "./api.js";
import { } from "./toggle-todo.js";
export function ({ }: { readonly : }) {
const { , , } = ();
return (
<
="checkbox"
={.}
={.}
={async () => {
const = await ({
: { : . },
: { : .. },
});
if (.()) {
(, 3000);
}
}}
/>
);
}useMutation returns a UseMutationResult:
result, theAsyncResultof this component's latest run:Initialbefore the first run and afterreset;variables, the variables of the runresultshows, orundefinedbefore the first run and afterreset;run(variables, options?), which starts a run and returns aPromiseof itsExit, Effect's value for a success or a failure with itsCause;reset(), which putsresultback toInitial. Runs in progress carry on;status,data,errorandcause, the latest run as fields, as TanStack Query'suseMutationreturns them, withisIdle,isPending,isSuccessandisFailureto match.
status is "idle" before the first run and after reset, "pending"
while a run is in progress, then "success" or "failure". data and
error are undefined while a newer run is pending, and error is
undefined for a run that died or was interrupted, which only cause
holds. Unlike useQueryState's, status doesn't
narrow data and error, so check them, or match on result.
run never rejects: check the Exit it resolves with. A run carries on if
the component unmounts, so the mutation's onSuccess and invalidates
still happen. A few runs end without running at all, or are cut short:
- With
concurrent: false, a run that a newer one replaces resolves with an interruptedExit. - With
concurrent: "drop", a run started while the oneresultshows is saving resolves at once with an interruptedExit. - On a disposed client, the run never starts and resolves with a died
Exit.
When runs overlap explains concurrent. Outside a
QueryProvider, useMutation throws a MissingQueryProviderError.
Add callbacks for one run
run also takes callbacks for one run, a UseMutationRunOptions, as
TanStack Query's mutate(variables, { onSuccess }) does:
import { } from "@monarcode/effetch-query/react";
import type { } from "./api.js";
import { } from "./toggle-todo.js";
export function ({
,
,
}: {
readonly : ;
readonly : () => void;
}) {
const { , } = ();
return (
<
="button"
={.}
={() =>
(
{ : { : . }, : { : true } },
{ : },
)
}
>
Done
</>
);
}onSuccess, onFailure and onSettled run after the mutation's own
callbacks, its invalidates and the client's hooks, before code awaiting
run carries on. They belong to this screen, so they're dropped if any of
these happens before the run settles:
resetis called;- a newer run starts;
- the component unmounts.
They're dropped for a run that was interrupted or never started, too. The
run completes all the same. A callback that throws is logged with
console.error; the ones after it still run, and run still resolves.
Because a newer run drops them, two quick clicks call only the second click's callbacks, even though both runs complete.
So use them for what matters only to this screen, such as filling in a
form field or navigating, and the mutation's own onSuccess for what must
always happen. A form that calls reset when its input changes never
fills in an answer for the old input. If the lookup only reads, make it a
query keyed by its input instead, read with
useQuery(input === "" ? null : lookup(input)).
When runs overlap
A component can start a run while its previous run is still saving, such
as on a second click of a button. The mutation's concurrent option
decides what happens. It applies to the runs of one use, such as one
component's useMutation: separate uses, and Mutation.run calls, never
affect each other.
concurrent takes one of four values:
true, the default: runs overlap, and each completes. Use it when each run is a change of its own.resultandvariablesfollow the latest run started.false: a new run replaces the one in progress. Use it when only the last value matters, such as a setting saved on each change. The run in progress is interrupted, and its optimistic writes are rolled back, before the new one starts. Interrupting it doesn't undo a request the server already received. A new run replaces the last one started even afterreset."queue": runs go one at a time, in order. Use it when every change must reach the server in the order it was made, such as reordering a list. A queued run counts as in progress, soresultstays waiting until the last one settles. Itsoptimisticruns when it starts, so a run that fails undoes only its own writes."drop": a run started while the oneresultshows is in progress is ignored. Use it for a submit button, where a second click shouldn't send the form twice. A dropped run never starts or calls anything. Afterreset, a new run starts.
Here a second click on "Add" while the first is saving does nothing:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "./api.js";
import { , } from "./todos.js";
export const = .(
.("POST /todos", {
: .({ : . }),
: ,
}),
// A click while the first run is saving does nothing.
{ : "drop", : [] },
);To pick a mode for every mutation, set it on the client:
mutations: { defaults: { concurrent: false } }. A mutation's own
concurrent overrides it.
Run from Effect
Mutation.run(mutation, variables) runs a mutation from Effect code, with
the same steps, and succeeds or fails
as its run did. A mutation whose run takes no variables runs without
them. Here a bulk action marks several todos done, one after another:
import * as from "effect/Effect";
import { } from "@monarcode/effetch-query";
import { } from "./client.js";
import { } from "./toggle-todo.js";
const = (: <number>) =>
.(
,
() => .(, { : { }, : { : true } }),
{ : true },
);
// From an event handler, through the client.
export const = (: <number>) =>
.(());Each Mutation.run is a run of its own, so concurrent doesn't apply:
calls never interrupt each other. Runs started this way count in
useIsMutating and useMutationState, as
Show activity describes.
What's next
- Invalidate after a mutation: refetch what a run changed.
- Optimistic updates: show the change before the server confirms it.
- Show activity: show what's saving anywhere in the app.