Skip to the content

commitMutation

A Promise wrapper around relay-runtime's commitMutation. It resolves with the mutation response. It rejects when Relay calls onError, and when onCompleted receives a non-empty errors array, so a GraphQL failure is a rejected promise rather than a resolved payload.
Relay

When to use

Use when
  • a submit or click handler fires a mutation and handles success or failure inline;
  • a test should await the mutation instead of mocking callbacks.
Avoid when
  • you need intermediate @defer payloads — call relay-runtime's commitMutation; this wrapper waits for a single onCompleted;
  • you subscribe to updates — use requestSubscription; a subscription has no end a Promise can represent.

Usage

import { commitMutation } from '@apollion-dsi/relay/commitMutation';
import SaveMutationNode, { type SaveMutation } from './__generated__/SaveMutation.graphql';
import { Environment } from './environment';

export async function save(input: SaveMutation['variables']['input']) {
  const response = await commitMutation<SaveMutation>(Environment, {
    mutation: SaveMutationNode,
    variables: { input },
  });
  return response.save?.ok;
}

mutation takes the generated artifact or a graphql tagged template. The config is relay-runtime's MutationConfig without onCompleted and onError: updater, optimisticResponse, optimisticUpdater and uploadables pass through unchanged. Inside a component, take the environment from useEnvironment().

Types

The package also exports its configuration types, from @apollion-dsi/relay/relayArgsInterface or the root entry:

  • RelayArgsInterface — the options of CreateRelayEnvironment, including graphqlErrorPolicy. Import it to type a configuration object built apart from the constructor. Every option is listed on CreateRelayEnvironment.
  • RelayInitialRecords — the type of the initialRecords option.
  • Sink — the minimal Relay Observable sink (next, error, complete, closed) used by the fetch and subscription handlers.
import { CreateRelayEnvironment } from '@apollion-dsi/relay/setupRelayEnvironment';
import type { RelayArgsInterface } from '@apollion-dsi/relay/relayArgsInterface';

const base: RelayArgsInterface = { url: 'https://api.example.com/graphql/', useRetries: true };

export const { Environment } = new CreateRelayEnvironment({ ...base, useDebug: true });

See also