Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Components: apollo-mutation

Provides a way to declare mutations and their variables, including input components.

Inherits from ApolloMutationInterface

Live Demo

<apollo-client uri="https://api.spacex.land/graphql">
  <p-card>
    <h2 slot="heading">Add a User</h2>
    <p>Complete the form to add a user.</p>

    <h3>Latest 5 Users</h3>
    <latest-users limit="5"></latest-users>

    <apollo-mutation slot="actions" refetch-queries="LatestUsers">
      <mwc-textfield slot="variable"
          data-variable="name"
          label="User name"
          outlined></mwc-textfield>
      <mwc-button slot="trigger" label="Add user"></mwc-button>
      <script type="application/graphql">
        mutation InsertUser($name: String!) {
          insert_users(objects: {name: $name}) {
            returning {
              name
              id
              timestamp
            }
          }
        }
      </script>
    </apollo-mutation>
  </p-card>
</apollo-client>

Some Markdown Before Properties

Some Markdown Before Slots

  • slot
  • slot
  • slot

Exports

import '@apollo-elements/components/apollo-mutation';
import { ApolloMutationElement } from '@apollo-elements/components/apollo-mutation';

Simple Mutation component that takes a button or link-wrapped button as it's trigger. When loading, it disables the button. On error, it toasts a snackbar with the error message. You can pass a variables object property, or if all your variables properties are strings, you can use the element's data attributes

Example: Using data attributes

<apollo-mutation data-type="Type" data-action="ACTION">
  <mwc-button slot="trigger">OK</mwc-button>
</apollo-mutation>

Will mutate with the following as variables:

{
  "type": "Type",
  "action": "ACTION"
}

Example: Using data attributes and variables

<apollo-mutation data-type="Quote" data-action="FLUB">
  <mwc-button slot="trigger" label="OK"></mwc-button>
  <mwc-textfield slot="variable"
      data-variable="name"
      value="Neil"
      label="Name"></mwc-textfield>
  <mwc-textarea slot="variable"
      data-variable="comment"
      value="That's one small step..."
      label="comment"></mwc-textarea>
</apollo-mutation>

Will mutate with the following as variables:

{
  "name": "Neil",
  "comment": "That's one small step...",
  "type": "Quote",
  "action": "FLUB"
}

Example: Using data attributes and variables with input property

<apollo-mutation data-type="Type" data-action="ACTION" input-key="actionInput">
  <mwc-button slot="trigger" label="OK"></mwc-button>
  <mwc-textfield slot="variable"
      data-variable="comment"
      value="Hey!"
      label="comment"></mwc-textfield>
</apollo-mutation>

Will mutate with the following as variables:

{
  "actionInput": {
    "comment": "Hey!",
    "type": "Type",
    "action": "ACTION"
  }
}

Example: Using DOM properties

<apollo-mutation id="mutation">
  <mwc-button slot="trigger" label="OK"></mwc-button>
</apollo-mutation>
<script>
  document.getElementById('mutation').mutation = SomeMutation;
  document.getElementById('mutation').variables = {
    type: "Type",
    action: "ACTION"
  };
</script>

Will mutate with the following as variables:

{
  "type": "Type",
  "action": "ACTION"
}

Properties

protected

button

(read-only)
ButtonLikeElement | null

The slotted button

If the slotted trigger node is a button, this is the trigger. If the slotted trigger node is a link with a button as it's first child, this is the button.

protected

href

(read-only)
string|undefined

The href attribute of the link trigger. The element will navigate to his URL on mutation completion.

inputKey

input-key
string

When set, variable data attributes will be packed into an object property with the name of this property

<apollo-mutation id="a" data-variable="var"></apollo-mutation>
<apollo-mutation id="b" input-key="input" data-variable="var"></apollo-mutation>
<script>
  console.log(a.variables) // { variable: 'var' }
  console.log(b.variables) // { input: { variable: 'var' } }
</script>
protected

inputs

(read-only)
InputLikeElement[]

Variable input elements.

An array of all the input-like elements slotted as variables (e.g. <input/> or <custom-input>). Custom inputs must have a value property corresponding to the input's value.

protected

trigger

(read-only)
HTMLElement | null

Slotted trigger node.

Slot in a button-like element (e.g. <button> or <custom-button>). When clicked, the element will mutate. Slot in a link (<a href>) to make this element navigate on mutation completion.

awaitRefetchQueries

(optional)
inherited from ApolloMutation
boolean

Queries refetched as part of refetchQueries are handled asynchronously, and are not waited on before the mutation is completed (resolved). Setting this to true will make sure refetched queries are completed before the mutation is considered done. false by default.

called

inherited from ApolloMutation
boolean

Whether the mutation was called

client

inherited from ApolloElementInterface
ApolloClient<NormalizedCacheObject> | null

The Apollo Client instance

Defaults to window.__APOLLO_CLIENT__, which is set by default when creating an Apollo Client. That means that in most cases, it's not necessary to explicity set the client property. For more information see Getting Started: Apollo Client.

context

(optional)
inherited from ApolloElementInterface
Record<string, unknown>

Context passed to the link execution chain.

data

inherited from ApolloElementInterface
Data<D> | null

Latest mutation data.

document

inherited from ApolloElementInterface
DocumentNode | TypedDocumentNode | null

A GraphQL document containing a single query, mutation, or subscription. You can set it as a JavaScript property or by appending a GraphQL script to the element (light DOM).

static

documentType

inherited from ApolloElementInterface
'mutation'

Hint that this is a mutation component

error

(optional)
inherited from ApolloElementInterface
Error | ApolloError | null

Latest error

errorPolicy

(optional)
inherited from ApolloElementInterface
ErrorPolicy

Specifies the Error Policy to be used for this mutation.

Much like fetchPolicy, errorPolicy allows you to control how GraphQL Errors from the server are sent to your UI code. By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn't save any data in the cache, and renders your UI with the error property set to an ApolloError. By changing this policy per request, you can adjust how GraphQL Errors are managed by your UI. The possible options for errorPolicy are:

  • none: This is the default policy to match how Apollo Client 1.0 worked. Any GraphQL Errors are treated the same as network errors and any data is ignored from the response.
  • ignore: Ignore allows you to read any data that is returned alongside GraphQL Errors, but doesn't save the errors or report them to your UI.
  • all: Using the all policy is the best way to notify your users of potential issues while still showing as much data as possible from your server. It saves both data and errors so your UI can use them.

errors

(optional)
inherited from ApolloElementInterface
readonly GraphQLError[] | null

Latest errors.

fetchPolicy

(optional)
inherited from ApolloMutation
Extract<FetchPolicy, 'no-cache'>

Specifies the FetchPolicy to be used for this mutation.

ignoreResults

(optional)
inherited from ApolloMutation
boolean

If true, the returned data property will not update with the mutation result.

loading

inherited from ApolloElementInterface
boolean

Whether a request is in-flight.

mutation

inherited from ApolloMutation
DocumentNode | TypedDocumentNode

A GraphQL document containing a single mutation. You can set it as a JavaScript property or by appending a GraphQL script to the element (light DOM).

<script type="application/graphql">
  mutation { updateLastSeen }
</script>

optimisticResponse

inherited from ApolloMutation
Data<D> | ((vars: Variables<D, V>) => Data<D>)

An object that represents the result of this mutation that will be optimistically stored before the server has actually returned a result.

This is most often used for optimistic UI, where we want to be able to see the result of a mutation immediately, and update the UI later if any errors appear.

element.optimisticResponse = ({ name }: HelloMutationVariables) => ({
  __typename: 'Mutation',
  hello: {
    __typename: 'Greeting',
    name,
  },
});

refetchQueries

inherited from ApolloMutation
RefetchQueriesType<D> | null

A list of query names which will be refetched once this mutation has returned. This is often used if you have a set of queries which may be affected by a mutation and will have to update. Rather than writing a mutation query reducer (i.e. updateQueries) for this, you can refetch the queries that will be affected and achieve a consistent store once these queries return.

variables

inherited from ApolloElementInterface
Variables<D, V> | null

An object that maps from the name of a variable as used in the mutation GraphQL document to that variable's value.

Methods

protected

getVariablesFromInputs

Constructs a variables object from the element's data-attributes and any slotted variable inputs.

Returns

Variables<D, V> | null

resolveURL

(optional)

Define this function to determine the URL to navigate to after a mutation. Function can be synchronous or async. If this function is not defined, will navigate to the href property of the link trigger.

Example: Navigate to a post's page after creating it

<apollo-mutation id="mutation">
  <script type="application/graphql">
    mutation CreatePostMutation($title: String, $content: String) {
      createPost(title: $title, content: $content) {
        slug
      }
    }
  </script>
  <mwc-textfield label="Post title" slot="variable" data-variable="title"></mwc-textfield>
  <mwc-textarea label="Post Content" slot="variable" data-variable="content"></mwc-textarea>
</apollo-mutation>

<script>
  document.getElementById('mutation').resolveURL =
    data => `/posts/${data.createPost.slug}/`;
</script>

Parameters

data

Data<D>

mutation data

Returns

string|Promise<string>

url to navigate to.

protected

documentChanged

(optional)
inherited from ApolloElementInterface

Lifecycle callback that reacts to changes in the GraphQL document.

Parameters

document

DocumentNode | TypedDocumentNode | null

The GraphQL document.

Returns

void
async

mutate

inherited from ApolloMutation

This resolves a single mutation according to the options specified and returns a Promise which is either resolved with the resulting data or rejected with an error.

Parameters

params

Partial<MutationOptions<Data<D>, Variables<D, V>>>

Optional, partial mutation params

All named arguments to mutate default to the element's corresponding instance property. So you can call element.mutate() without arguments and it will call using element.mutation, element.variables, etc. You can likewise override instance properties per-call by passing them in, e.g.

await element.mutate({
  fetchPolicy: 'network-only'
  variables: {
    ...element.variables,
    name: 'overridden',
  },
});
Property Type Description
awaitRefetchQueries
boolean
See awaitRefetchQueries
context
Record<string, unknown>
See context
errorPolicy
ErrorPolicy
See errorPolicy
fetchPolicy
FetchPolicy
See fetchPolicy
mutation
DocumentNode | TypedDocumentNode
See mutation
optimisticResponse
OptimisticResponseType<D, V>
See optimisticResponse
refetchQueries
RefetchQueriesType<D>
See refetchQueries
update
MutationUpdaterFn<Data<D>> 
See updater
variables
Variables<D, V> 
See variables

Returns

Promise<FetchResult<Data<D>>>

A FetchResult object containing the result of the mutation and some metadata.

Property Type Description
data
Data<D>
The result of a successful execution of the mutation
errors
readonly GraphQLError[]
included when any errors occurred as a non-empty array
extensions
boolean
Reserved for adding non-standard properties
context
Record<string, unknown>
See context

onCompleted

(optional)
inherited from ApolloMutation

Callback for when a mutation is completed.

Parameters

data

Data<D>

Returns

void

onError

(optional)
inherited from ApolloMutation

Callback for when an error occurs in mutation.

Parameters

error

Error

Returns

void

updater

(optional)
inherited from ApolloMutation

This function will be called twice over the lifecycle of a mutation. Once at the very beginning if an optimisticResponse was provided. The writes created from the optimistic data will be rolled back before the second time this function is called which is when the mutation has succesfully resolved. At that point update will be called with the actual mutation result and those writes will not be rolled back.

Note that since this function is intended to be used to update the store, it cannot be used with a no-cache fetch policy. If you're interested in performing some action after a mutation has completed, and you don't need to update the store, use the Promise returned from client.mutate instead.

Parameters

cache

ApolloCache

Use the cache.writeQuery, cache.writeFragment, etc. methods to update the cache following the mutation.

result

FetchResult<Data<D>>

See mutate

Property Type Description
data
Data<D>
The result of a successful execution of the mutation
errors
readonly GraphQLError[]
included when any errors occurred as a non-empty array
extensions
boolean
Reserved for adding non-standard properties
context
Record<string, unknown>
See context

Returns

void
protected

variablesChanged

(optional)
inherited from ApolloElementInterface

Lifecycle callback that reacts to changes in the operation variables.

Parameters

variables

Variables<D, V> | null

The variables.

Returns

void

Slots

trigger

The triggering element. Must be a button or and anchor that wraps a button.

variables

An input with a data-variable attribute. It's value property gets the value for the corresponding variable.

CSS Shadow Parts

Name Description
trigger The container for variable inputs.
variables The container for variable inputs.

Events

Name Type Description
mutation-completed
CustomEvent<{ data: Data, element: this }>

When the mutation resolves.

mutation-error
CustomEvent<{ error: ApolloError, element: this }>

When the mutation rejects.

will-mutate
CustomEvent<{ element: this }>

When the element is about to mutate. Useful for setting variables. Prevent default to prevent mutation.

will-navigate
CustomEvent<{ data: Data, element: this }>

When the mutation resolves and the element is about to navigate. cancel the event to handle navigation yourself e.g. using a client-side router.