Skip to Content
Effetch Query
Mutations

Define a mutation

Define a mutation from an Effetch endpoint or an Effect.

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.

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:

import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

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

export const  = .(
  .("POST /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 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 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:

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

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

export const  = .({
  : (: ) =>
    .(() =>
      .("/todos/:id", {
        : { : . },
        : { : !. },
        : ,
      }),
    ),
  // A key reaches every query under it, endpoint or not.
  : [["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:

import * as  from "effect/Schema";

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

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

const  = .({ : ., : . });

export const  = .(
  .("POST /documents", {
    : .(
      .({ : ., : . }),
    ),
    : ,
  }),
);

export function () {
  const { ,  } = ();
  return (
    <
      ="file"
      ={.}
      ={() => {
        const  = ..?.[0];
        // Cleared, so picking the same file again uploads it again.
        .. = "";
        if ( !== ) {
          void ({ : { , : "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 shows. The client's hooks run on every run of every mutation, as Defaults and app-wide hooks 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 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

On this page