# Run a mutation (https://effetch-query.monarcode.dev/docs/mutations/run)

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](https://effetch-query.monarcode.dev/docs/getting-started).

## Run from a component

This checkbox toggles a todo, and clears a failure after three seconds:

```tsx
import * as Exit from "effect/Exit";

import { useMutation } from "@monarcode/effetch-query/react";

import type { Todo } from "./api.js";
import { toggleTodo } from "./toggle-todo.js";

export function DoneCheckbox({ todo }: { readonly todo: Todo }) {
  const { result, run, reset } = useMutation(toggleTodo);

  return (
    <input
      type="checkbox"
      checked={todo.done}
      disabled={result.waiting}
      onChange={async (event) => {
        const exit = await run({
          params: { id: todo.id },
          body: { done: event.target.checked },
        });
        if (Exit.isFailure(exit)) {
          setTimeout(reset, 3000);
        }
      }}
    />
  );
}
```

`useMutation` returns a `UseMutationResult`:

- `result`, the `AsyncResult` of this component's latest run: `Initial`
  before the first run and after `reset`;
- `variables`, the variables of the run `result` shows, or `undefined`
  before the first run and after `reset`;
- `run(variables, options?)`, which starts a run and returns a `Promise` of
  its `Exit`, Effect's value for a success or a failure with its `Cause`;
- `reset()`, which puts `result` back to `Initial`. Runs in progress carry
  on;
- `status`, `data`, `error` and `cause`, the latest run as fields, as
  TanStack Query's `useMutation` returns them, with `isIdle`, `isPending`,
  `isSuccess` and `isFailure` to 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`](https://effetch-query.monarcode.dev/docs/react/as-object)'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 interrupted `Exit`.
- With `concurrent: "drop"`, a run started while the one `result` shows
  is saving resolves at once with an interrupted `Exit`.
- On a disposed client, the run never starts and resolves with a died
  `Exit`.

[When runs overlap](https://effetch-query.monarcode.dev/docs/mutations/run#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:

```tsx
import { useMutation } from "@monarcode/effetch-query/react";

import type { Todo } from "./api.js";
import { toggleTodo } from "./toggle-todo.js";

export function MarkDone({
  todo,
  onDone,
}: {
  readonly todo: Todo;
  readonly onDone: () => void;
}) {
  const { result, run } = useMutation(toggleTodo);

  return (
    <button
      type="button"
      disabled={result.waiting}
      onClick={() =>
        run(
          { params: { id: todo.id }, body: { done: true } },
          { onSuccess: onDone },
        )
      }
    >
      Done
    </button>
  );
}
```

`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:

- `reset` is 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. `result` and `variables` follow 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
  after `reset`.
- **`"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, so `result` stays waiting
  until the last one settles. Its `optimistic` runs when it starts, so a
  run that fails undoes only its own writes.
- **`"drop"`: a run started while the one `result` shows 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. After
  `reset`, a new run starts.

Here a second click on "Add" while the first is saving does nothing:

```ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

import { Todo } from "./api.js";
import { api, todos } from "./todos.js";

export const createTodo = api.mutation(
  Fetch.endpoint("POST /todos", {
    input: Schema.Struct({ title: Schema.String }),
    output: Todo,
  }),
  // A click while the first run is saving does nothing.
  { concurrent: "drop", invalidates: [todos] },
);
```

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](https://effetch-query.monarcode.dev/docs/mutations#what-a-run-does), 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:

```ts
import * as Effect from "effect/Effect";

import { Mutation } from "@monarcode/effetch-query";

import { queryClient } from "./client.js";
import { toggleTodo } from "./toggle-todo.js";

const markAllDone = (ids: ReadonlyArray<number>) =>
  Effect.forEach(
    ids,
    (id) => Mutation.run(toggleTodo, { params: { id }, body: { done: true } }),
    { discard: true },
  );

// From an event handler, through the client.
export const onMarkAllDone = (ids: ReadonlyArray<number>) =>
  queryClient.runPromise(markAllDone(ids));
```

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](https://effetch-query.monarcode.dev/docs/mutations/activity) describes.

## What's next

- [Invalidate after a mutation](https://effetch-query.monarcode.dev/docs/mutations/invalidate): refetch what
  a run changed.
- [Optimistic updates](https://effetch-query.monarcode.dev/docs/mutations/optimistic): show the change before
  the server confirms it.
- [Show activity](https://effetch-query.monarcode.dev/docs/mutations/activity): show what's saving anywhere
  in the app.