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>
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
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.
href
(read-only)string|undefined
The href
attribute of the link trigger. The element will navigate to his URL on mutation completion.
inputKey
input-keystring
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>
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.
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 ApolloMutationboolean
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 ApolloMutationboolean
Whether the mutation was called
client
inherited from ApolloElementInterfaceApolloClient<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 ApolloElementInterfaceRecord<string, unknown>
Context passed to the link execution chain.
data
inherited from ApolloElementInterfaceData<D> | null
Latest mutation data.
document
inherited from ApolloElementInterfaceDocumentNode | 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).
documentType
inherited from ApolloElementInterface'mutation'
Hint that this is a mutation component
error
(optional) inherited from ApolloElementInterfaceError | ApolloError | null
Latest error
errorPolicy
(optional) inherited from ApolloMutationErrorPolicy
Specifies the ErrorPolicy
to be used for this mutation.
errors
(optional) inherited from ApolloElementInterfacereadonly GraphQLError[] | null
Latest errors.
fetchPolicy
(optional) inherited from ApolloMutationExtract<FetchPolicy, 'no-cache'>
Specifies the FetchPolicy to be used for this mutation.
ignoreResults
(optional) inherited from ApolloMutationboolean
If true, the returned data property will not update with the mutation result.
loading
inherited from ApolloElementInterfaceboolean
Whether a request is in-flight.
mutation
inherited from ApolloMutationDocumentNode | 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 ApolloMutationData<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 ApolloMutationRefetchQueriesType<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 ApolloElementInterfaceVariables<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
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.
documentChanged
(optional) inherited from ApolloElementInterfaceLifecycle callback that reacts to changes in the GraphQL document.
Parameters
document
DocumentNode | TypedDocumentNode | null
The GraphQL document.
Returns
void
mutate
inherited from ApolloMutationThis 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 |
|
See awaitRefetchQueries |
context |
|
See context |
errorPolicy |
|
See errorPolicy |
fetchPolicy |
|
See fetchPolicy |
mutation |
|
See mutation |
optimisticResponse |
|
See optimisticResponse |
refetchQueries |
|
See refetchQueries |
update |
|
See updater |
variables |
|
See variables |
Returns
Promise<FetchResult<Data<D>>>
A FetchResult
object containing the result of the mutation and some metadata.
Property | Type | Description |
---|---|---|
data |
|
The result of a successful execution of the mutation |
errors |
|
included when any errors occurred as a non-empty array |
extensions |
|
Reserved for adding non-standard properties |
context |
|
See context |
onCompleted
(optional) inherited from ApolloMutationCallback for when a mutation is completed.
Parameters
data
Data<D>
Returns
void
onError
(optional) inherited from ApolloMutationCallback for when an error occurs in mutation.
Parameters
error
Error
Returns
void
updater
(optional) inherited from ApolloMutationThis 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 |
|
The result of a successful execution of the mutation |
errors |
|
included when any errors occurred as a non-empty array |
extensions |
|
Reserved for adding non-standard properties |
context |
|
See context |
Returns
void
variablesChanged
(optional) inherited from ApolloElementInterfaceLifecycle 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 |
|
When the mutation resolves. |
mutation-error |
|
When the mutation rejects. |
will-mutate |
|
When the element is about to mutate. Useful for setting variables. Prevent default to prevent mutation. |
will-navigate |
|
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. |