Skip to Content
Effetch Query
Mutations

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, 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'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 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:

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

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

On this page