# Optimistic updates (https://effetch-query.pages.dev/docs/mutations/optimistic)

A checkbox that waits for the server feels slow. An optimistic update
shows the change before the server confirms it, and takes it back if the
request fails. You can show it in the component that runs the mutation,
or write it to the cache, where every screen shows it. This page shows
both, and what a rollback doesn't cover.

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

## Show the change 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, as
[Wait for the refetch](https://effetch-query.pages.dev/docs/mutations/invalidate#wait-for-the-refetch)
explains:

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

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

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

const createTodo = api.mutation(
  Fetch.endpoint("POST /todos", {
    input: Schema.Struct({ title: Schema.String }),
    output: Todo,
  }),
  // Refetches the lists and waits, so the run settles after they have it.
  { onSuccess: () => Query.refetch(todos) },
);

export function AddTodo({ title }: { readonly title: string }) {
  const { result, variables, run } = useMutation(createTodo);

  return (
    <>
      {result.waiting && variables !== undefined ? (
        <li style={{ opacity: 0.5 }}>{variables.body.title}</li>
      ) : null}
      <li>
        <button type="button" onClick={() => void run({ body: { title } })}>
          Add
        </button>
      </li>
    </>
  );
}
```

If the run fails, the faded todo goes, and there's nothing to undo. Only
this component shows it. Another component can list the runs in progress
with `useMutationState`, as [Show activity](https://effetch-query.pages.dev/docs/mutations/activity)
describes.

## Write the change to the cache

To show the change everywhere the data is cached, write the cache in the
mutation's `optimistic` option. If the request fails, every write it made
is undone, newest first. This version of Getting started's `toggleTodo`
flips the todo at once, in its own query and in every cached list, with
`Query.update`:

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

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

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

export const toggleTodo = api.mutation(
  Fetch.endpoint("PATCH /todos/:id", {
    input: Schema.Struct({ done: Schema.Boolean }),
    output: Todo,
  }),
  {
    optimistic: ({ params: { id }, body: { done } }) =>
      Effect.andThen(
        // The todo's own query.
        Query.update(todo({ params: { id: Number(id) } }), (current) => ({
          ...current,
          done,
        })),
        // Each cached list, whatever its filter.
        Query.update(todos, (list) =>
          list.map((item) =>
            item.id === Number(id) ? { ...item, done } : item,
          ),
        ),
      ),
    // The server's version replaces the guess.
    onSuccess: (saved) => Query.set(todo({ params: { id: saved.id } }), saved),
    invalidates: [todos],
  },
);
```

An entity does the same in fewer lines. An entity is a schema with an ID,
such as the `Todos` entity for `Todo`, and one write to it reaches every
cached copy of a record, in whichever query holds it, as
[Entities](https://effetch-query.pages.dev/docs/cache/entities) explains. Here is the same `toggleTodo`
with the entity:

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

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

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

export const toggleTodo = api.mutation(
  Fetch.endpoint("PATCH /todos/:id", {
    input: Schema.Struct({ done: Schema.Boolean }),
    output: Todo,
  }),
  {
    // Every cached copy: its own query, and each list, whatever its filter.
    optimistic: ({ params, body }) =>
      Entity.update(Todos, Number(params.id), (todo) => ({
        ...todo,
        done: body.done,
      })),
    // The server's version replaces the guess.
    onSuccess: (saved) => Entity.set(Todos, saved),
    invalidates: [todos],
  },
);
```

Either way, a written value shows until the next fetch of that query
settles, so the old value never flashes back while the refetch runs. Both
versions replace `toggle-todo.ts`'s `toggleTodo`: define one mutation per
change in your app.

## What a rollback doesn't cover

A failed run puts back what its `optimistic` wrote, with three limits:

- **Only writes made while `optimistic` runs are undone:** not those of a
  fiber it forks that write after it's done, nor those of a mutation it
  runs.
- **A query written again in the meantime is put back all the same,**
  even when a fetch wrote it.
- **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.

## What's next

- [Entities](https://effetch-query.pages.dev/docs/cache/entities): define the `Todos` entity, and write
  or read a record by its ID.
- [When runs overlap](https://effetch-query.pages.dev/docs/mutations/run#when-runs-overlap): what a
  second click does while the first run is saving.
- [The cache](https://effetch-query.pages.dev/docs/cache): every function that reads and writes the
  cache.