Docs
commitMutation

commitMutation

Promise-based wrapper around relay-runtime's commitMutation. Lets you use Relay mutations with async/await instead of orchestrating onCompleted / onError.

When to use

✅ Use when…🚫 Avoid when…
  • When you want to fire a Relay mutation inside an async handler (form submit, click handler, effect) and handle success/error with try/catch.
  • In tests, where awaiting the Promise is much simpler than mocking callbacks.
  • When you need intermediate feedback (onNext in mutations with @defer). In that case use the raw commitMutation from relay-runtime.
  • For subscriptions. Use Relay's requestSubscription directly — a subscription has no "end" representable by a Promise.

Example

import { commitMutation } from '@apollion-dsi/relay/commitMutation';
import { Environment } from './environment';
import { MyMutation } from './__generated__/MyMutation.graphql';
 
async function save(input: MyMutation['variables']['input']) {
  try {
    const response = await commitMutation<MyMutation>(Environment, {
      mutation: graphql`
        mutation MyMutation($input: MyInput!) {
          myMutation(input: $input) {
            ok
          }
        }
      `,
      variables: { input },
    });
    return response.myMutation.ok;
  } catch (error) {
    console.error('mutation failed', error);
    throw error;
  }
}

Granular imports

This module can be imported in two ways:

// Granular — recommended when the consumer only needs this function.
import { commitMutation } from '@apollion-dsi/relay/commitMutation';
 
// Via the root barrel — more convenient, brings in more code.
import { commitMutation } from '@apollion-dsi/relay';

See also