Apollo Elements Guides API Blog

Haunted: useMutation

Apollo useMutation hook for web components. Elements that call useMutation inherit the ApolloMutationInterface.

Read the mutation component guides for examples and tips.

Live Demo

import { useMutation } from '@apollo-elements/haunted/useMutation';
import { useState, component, html } from 'haunted';
import AddUserMutation from './AddUser.mutation.graphql';

function AddUser() {
  const [addUser, { called, data }] = useMutation(AddUserMutation);
  const [variables, setVariables] = useState({ });

  const onInput = event => setVariables({ name: event.target.value }));
  return html`
    <p-card>
      <h2 slot="heading">Add User</h2>

      ${!called || !data ? '' : html`
      <dl>
        <dt>Name</dt>    <dd>${data.name}</dd>
        <dt>Added</dt> <dd>${new Date(data.timestamp).toDateString()}</dd>
      </dl>
      `}

      <mwc-textfield slot="actions"
          label="User Name"
          outlined
          @input="${onInput}"></mwc-textfield>
      <mwc-button slot="actions"
          label="Add User"
          @input="${onInput}"></mwc-button>
    </p-card>
  `;
}

customElements.define('add-user', component(AddUser));

Elements that call useMutation inherit the ApolloMutationInterface.

Read the mutation component guides for examples and tips.

Exports

import { useMutation } from '@apollo-elements/haunted/useMutation';

useMutation

Parameters

mutation

TypedDocumentNode|DocumentNode

The DocumentNode describing the mutation. If you pass a TypedDocumentNode, the data type will be inferred for you.

options

MutationHookOptions<D, V>

Options to control how the mutation executes

Option Type Description
client
ApolloClient
ApolloClient instance use to make the call.
mutation
DocumentNode | TypedDocumentNode
A specific mutation document. See mutation.
variables
Variables<D, V> 
Operation variables. See variables.
optimisticResponse
OptimisticResponseType<D, V>
See optimisticResponse
context
Record<string, unknown>
Context object passed through the link execution chain.
errorPolicy
ErrorPolicy
Error policy to use for the mutation. See errorPolicy
fetchPolicy
FetchPolicy
See fetchPolicy
refetchQueries See refetchQueries
awaitRefetchQueries
boolean
See awaitRefetchQueries
update Function used to update the client cache following the mutation. See updater.

Returns

[MutateFn<D, V>, MutationHookResult<D, V>]

Pair of mutation function and mutation result object containing data, error, loading, called, and client

Option Description
called Whether the mutation has been called
client A reference to the ApolloClient instance that made the call
data Mutation result. See data in ApolloMutationInterface
error Error thrown by the mutation attempt.
loading Whether the mutation request is in-flight.