<link rel="stylesheet" href="/_merged_assets/_static/search/noscript.css">
Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

ApolloMutation: Component Lifecycle

connectedCallback

On connecting to the DOM, the element reads it's mutation and variable properties either from JavaScript, or from it's script children, and initializes a MutationObserver to watch for changes to those children.

mutate

Call this method to initiate the mutation. You can call it without arguments, or with a partial MutationOptions object. The rest of the mutation options will fall back to the corresponding instance properties.

In other words, the following two snippets are equivalent:

element.optimisticResponse = ({ name }) => ({ __typename: 'Mutation', addUser: { name } });
element.variables = { name: 'Hulda' };
element.mutate();
element.mutate({
  optimisticResponse: ({ name }) => ({ __typename: 'Mutation', addUser: { name } }),
  variables: { name: 'Hulda' },
});

If another call is made to mutate before the first resolves, only the final call will set element instance properties.

element.addEventListener('apollo-mutation-result', event =>
  console.log(event.detail.data.addUser.name));
element.mutate({ variables: { name: 'Miriam' } });
element.mutate({ variables: { name: 'Devorah' } });
element.mutate({ variables: { name: 'Yael' } });
// => logs: 'Yael'

updater

Function which defines how to integrate the mutation result into the cache. For some simple cases Apollo can do this automatically, but for others you will need or want to control the process, for example, an AddPostMutation which adds a post to an array of Posts.

element.updater: MutationUpdaterFn<AddPostsMutationData, AddPostsMutationVariables> =
  (cache, result) => {
    const query = LatestPostsQuery;
    const cached = cache.readQuery({ query: LatestPostsQuery });
    const data = { posts: [result.data.postBlogPost, ...cached.posts] }
    cache.writeQuery({ query, data });
  }

onCompleted

The onCompleted callback is a unary function that takes a FetchResult.

onCompleted is called after the element instance' properties are set.

onError

The onError callback is a unary function that takes an Error or ApolloError.

onError is called after the element instance' properties are set.

Events

Listen for the apollo-mutation-result and apollo-error events to react to changes. They fire before the element instance' properties are set.

apollo-mutation-result

Detail is an FetchResult object.