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

Your app changes data on the server: it toggles a todo, adds one, uploads
a file. A mutation describes one such change, and what the cache should
do when it succeeds. This page shows how to define one from an Effetch
endpoint or from an Effect you write, and the order a run calls its
options in.

The examples import `api.ts` and `todos.ts` from
[Getting started](https://effetch-query.monarcode.dev/docs/getting-started).

## Define one from an endpoint

`api.mutation` takes an endpoint and a mutation's options, as `api.query`
does. Any method works. This one adds a todo, then marks every todo list
out of date:

```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,
  }),
  { invalidates: [todos] },
);
// run({ body: { title: "Buy milk" } })
```

The endpoint fills in what a mutation needs:

- **Its variables are the call's options:** `params`, `query`, `body`,
  `headers` and `plugins`, typed as `EndpointVariables`. A run of an
  endpoint that requires none of them takes no variables.
- **Its value and errors are typed from the endpoint and the client, as a
  query's are:** here a `Todo`, with the errors
  [Queries from endpoints](https://effetch-query.monarcode.dev/docs/queries#what-a-query-takes-from-its-endpoint)
  describes.
- **Its options are a mutation's options without `run`,** since the
  endpoint is the run, plus the `headers` and `plugins` that Effetch's
  `client.bind` takes. They're an `EndpointMutationOptions`, and
  [Mutation options](https://effetch-query.monarcode.dev/docs/mutations/options) lists them.

## Define one from an Effect

When there's no endpoint, `Mutation.make` defines a mutation from an
Effect you write. Here is Getting started's `toggleTodo`, written by hand,
with the todo to toggle as its variables:

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

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

export const toggleTodo = Mutation.make({
  run: (todo: Todo) =>
    ApiClient.use((client) =>
      client.patch("/todos/:id", {
        params: { id: todo.id },
        body: { done: !todo.done },
        output: Todo,
      }),
    ),
  // A key reaches every query under it, endpoint or not.
  invalidates: [["todos"]],
});
// useMutation(toggleTodo).run(todo)
```

Its types come from `run`, so annotate `run`'s parameter to type the
variables. If you give type arguments instead, give all three, since the
value and error types you leave out are `never`. Its options are a
`Mutation.MakeOptions`: `run`, and the options an endpoint mutation takes
except `headers` and `plugins`.

Either way, a definition holds no state, and nothing runs until it's used.
Each use keeps its own state, so two components that run `toggleTodo`
never share a waiting or failed state. Define mutations at module level,
as you do queries: a definition made on each render starts a new state
each time.

## Upload files

An endpoint whose `input` is wrapped in Effetch's `Fetch.multipart` sends
its body as `multipart/form-data`, and its mutation's `body` is typed by
the schema. `Fetch.UploadFile` is a file field: a `File` or `Blob`, or in
React Native the `{ uri, name, type }` a picker gives:

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

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

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

const Document = Schema.Struct({ id: Schema.Finite, name: Schema.String });

export const uploadDocument = api.mutation(
  Fetch.endpoint("POST /documents", {
    input: Fetch.multipart(
      Schema.Struct({ file: Fetch.UploadFile, kind: Schema.String }),
    ),
    output: Document,
  }),
);

export function UploadPassport() {
  const { run, result } = useMutation(uploadDocument);
  return (
    <input
      type="file"
      disabled={result.waiting}
      onChange={(event) => {
        const file = event.target.files?.[0];
        // Cleared, so picking the same file again uploads it again.
        event.target.value = "";
        if (file !== undefined) {
          void run({ body: { file, kind: "PASSPORT" } });
        }
      }}
    />
  );
}
```

## What a run does

Every run, from a component or from Effect, calls the mutation's options
and the client's `mutations` hooks in this order:

1. `optimistic`, whose cache writes are recorded;
2. the client's `mutations.onMutate`;
3. `run`, retried on `retry`;
4. on success: `onSuccess`, `invalidates`, then the client's
   `mutations.onSuccess`;
5. on failure: the optimistic writes are rolled back, then `onFailure`,
   then the client's `mutations.onFailure`;
6. `onSettled`, then the client's `mutations.onSettled`.

The callbacks you give to one `run` in a component come after all of
these, as [Run a mutation](https://effetch-query.monarcode.dev/docs/mutations/run) shows. The client's hooks
run on every run of every mutation, as
[Defaults and app-wide hooks](https://effetch-query.monarcode.dev/docs/client/defaults) shows.

A step can go wrong in two ways, and they end differently:

- **The mutation's own callback dies.** If `optimistic`, `onSuccess`,
  `onFailure` or `onSettled` dies, the run dies with that defect, and the
  steps after it don't happen. A run whose `optimistic` dies still has its
  writes rolled back.
- **A client hook or a per-run callback fails.** A client hook that dies
  is logged, and the run carries on. A per-run callback that throws is
  logged too, since the run has already settled.

A run can also be interrupted: replaced by a newer one under
`concurrent: false`, as [When runs overlap](https://effetch-query.monarcode.dev/docs/mutations/run#when-runs-overlap)
describes, or stopped when its client is disposed, which also interrupts
the runs `concurrent: "queue"` holds back. An interrupted run calls
nothing after the interruption. If its `run` hadn't succeeded yet, its
optimistic writes are rolled back, unless the client is being disposed:
then there's no cache left to put back.

## What's next

- [Run a mutation](https://effetch-query.monarcode.dev/docs/mutations/run): run it from a component or from
  Effect, and choose what happens when runs overlap.
- [Invalidate after a mutation](https://effetch-query.monarcode.dev/docs/mutations/invalidate): refetch the
  queries a change makes out of date.
- [Mutation options](https://effetch-query.monarcode.dev/docs/mutations/options): every option, with its
  default.