Skip to content
On this page

Custom Mutation creation

TIP

The process of creating custom factory for Mutation is similar to same process for Query.

Mutation is a simple object with that stores some reactive primitives — Event, Effect, and Store. It means you can create Mutation not only by built-in factories but by your own. E.g. 👇

ts
function createAsyncStorageMutation({ storageKey }) {
  const start = createEvent();

  const executeFx = createEffect((value) => asyncLocalStorage.setItem(storageKey, value));

  sample({ clock: start, target: executeFx });

  return { start, ... };
}

In this example, some Effector APIs were used to create QuerycreateEvent, createEffect.

Of course, it looks pretty verbose, so Farfetched provides a special helper that aims to simplify creation of custom Mutation factories — createHeadlessMutation. Let us rewrite provided example with this helper 👇

ts
import { createHeadlessMutation } from '@farfetched/core';

function createAsyncStorageMutation({ storageKey }) {
  const executeFx = createEffect((value) => asyncLocalStorage.setItem(storageKey, value));

  const headlessQuery = createHeadlessMutation(/*...*/);
  headlessQuery.__.executeFx.use(executeFx);

  return headlessQuery;
}

createHeadlessMutataion hides all logic to handle contracts and errors inside, so you only have to provide executor, which will be called to preform mutation.

Released under the MIT License.