Provides a way to declare mutations and their variables, including input components.
Inherits from ApolloMutationInterface
Live Demo
<script type="module" src="components.js"></script>
<apollo-client uri="https://api.spacex.land/graphql">
<apollo-mutation refetch-queries="LatestUsers">
<script type="application/graphql" src="InsertUser.mutation.graphql"></script>
<template>
<link rel="stylesheet" href="InsertUser.css"/>
<p-card>
<h2 slot="heading">Add a User</h2>
<p>Complete the form to add a user.</p>
<p ?hidden="{{ !data }}">{{ data.insert_users.returning[0].name }} added!</p>
<slot slot="actions"></slot>
</p-card>
</template>
<mwc-textfield data-variable="name" label="User name" outlined></mwc-textfield>
<mwc-button trigger label="Add user"></mwc-button>
</apollo-mutation>
</apollo-client>
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
See ApolloMutationInterface
for more information on events
Examples
<apollo-mutation data-type="Type" data-action="ACTION">
<mwc-button trigger>OK</mwc-button>
</apollo-mutation>
Will mutate with the following as variables
:
{
"type": "Type",
"action": "ACTION"
}
<apollo-mutation data-type="Quote" data-action="FLUB">
<mwc-button trigger label="OK"></mwc-button>
<mwc-textfield
data-variable="name"
value="Neil"
label="Name"></mwc-textfield>
<mwc-textarea
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"
}
<label>Comment <input variable-for="comment-mutation" value="Hey!"></label>
<button trigger-for="comment-mutation">OK</button>
<apollo-mutation id="comment-mutation"></apollo-mutation>
Will mutate with the following as variables
:
{ "comment": "Hey!" }
<apollo-mutation data-type="Type" data-action="ACTION" input-key="actionInput">
<mwc-button trigger label="OK"></mwc-button>
<mwc-textfield
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"
}
}
<apollo-mutation id="mutation">
<mwc-button 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
is
static(read-only)'apollo-mutation'
template
(read-only)HTMLTemplateElement | null
Template element to render. Can either be a light-DOM child of the element,
or referenced by ID with the template
attribute.
controller
ApolloController<D, V>
inputKey
string|null
input
.When set, variable data attributes will be packed into an object property with the name of this property
Examples
<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>
called
boolean
mutation
null | ComponentDocument<D, V>
context
Record<string, unknown> | undefined
optimisticResponse
OptimisticResponseType<D, V> | undefined
An object that represents the result of this mutation that will be optimistically stored before the server has actually returned a result, or a unary function that takes the mutation’s variables and returns such an object.
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.
Examples
element.optimisticResponse = ({ name }: HelloMutationVariables) => ({
__typename: 'Mutation',
hello: {
__typename: 'Greeting',
name,
},
});
variables
Variables<D, V> | null
ignoreResults
boolean
awaitRefetchQueries
boolean
errorPolicy
ErrorPolicy | undefined
fetchPolicy
'no-cache' | undefined
refetchQueries
RefetchQueriesType<D> | null
updateQueries
) for this,
you can refetch the queries that will be affected
and achieve a consistent store once these queries return.readyToReceiveDocument
boolean
client
ApolloClient<NormalizedCacheObject> | null
loading
boolean
data
Data<D> | null
document
ComponentDocument<D, V> | null
DocumentNode
error
Error | ApolloError | null
errors
readonly GraphQLError[]
templateHandlers
TemplateHandlers
Methods
resolveURL
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.
Examples
<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" data-variable="title"></mwc-textfield>
<mwc-textarea label="Post Content" data-variable="content"></mwc-textarea>
</apollo-mutation>
<script>
document.getElementById('mutation').resolveURL =
data => `/posts/${data.createPost.slug}/`;
</script>
Parameters
data
Data<D>
trigger
HTMLElement
Returns
updater
publicA function which updates the apollo cache when the query responds. 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.
The reason a DataProxy is provided instead of the user calling the methods directly on ApolloClient is that all of the writes are batched together at the end of the update, and it allows for writes generated by optimistic data to be rolled back.
Parameters
params
Parameters<MutationUpdaterFn<Data<D>, Variables<D, V>>>
Returns
ReturnType<MutationUpdaterFn<Data<D>, Variables<D, V>>>
mutate
publicParameters
params
Partial<MutationOptions<Data<D>, Variables<D, V>>>
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 |
See mutation |
optimisticResponse | OptimisticResponseType<D, V> |
See optimisticResponse |
refetchQueries | RefetchQueriesType<D, V> |
See refetchQueries |
update | MutationUpdaterFn<Data<D>, Variables<D, V>> |
See updater |
variables | Variables<D, V> |
See variables |
Returns
Promise<FetchResult<Data<D>>>
Property | Type | Description |
---|---|---|
data | Data<D, V> |
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 |
$
publicquerySelector
within the render root.Parameters
sel
string
Returns
E | null
$$
publicquerySelectorAll
within the render root.Parameters
sel
string
Returns
NodeListOf<E>
Events
WillMutateEvent
will-mutate
WillMutateEvent
The element is about to mutate. Useful for setting variables. Prevent default to prevent mutation. Detail is { element: this }
will-navigate
WillNavigateEvent
The mutation resolved and the element is about to navigate. cancel the event to handle navigation yourself e.g. using a client-side router. . detail
is { data: Data, element: this }
mutation-completed
MutationCompletedEvent
The mutation resolves. detail
is { data: Data, element: this }
mutation-error
MutationErrorEvent
The mutation rejected. detail
is { error: ApolloError, element: this }
apollo-element-disconnected
ApolloElementEvent
The element disconnected from the DOMapollo-element-connected
ApolloElementEvent
The element connected to the DOMPrivate Properties
inFlightTrigger
privateHTMLElement | null
doMutate
privatedebouncedMutate
private#buttonMO
privateMutationObserver | undefined
#listeners
private#root
private(read-only)ShadowRoot | Document | DocumentFragment | null
inputs
protected(read-only)InputLikeElement[]
triggers
protected(read-only)Element[]
buttons
protected(read-only)ButtonLikeElement[]
Private Methods
isButton
privateFalse when the element is a link.Parameters
node
Element|null
Returns
node is ButtonLikeElement
isLink
privateParameters
node
Element|null
Returns
node is HTMLAnchorElement
toVariables
privateParameters
acc
T
element
InputLikeElement
Returns
T
isTriggerNode
privateParameters
node
Node
Returns
node is HTMLElement
debounce
privateParameters
f
() => void
timeout
number
Returns
() => void
onLightDomMutation
privateParameters
records
MutationRecord[]
onSlotchange
privateReturns
void
addTriggerListener
privateParameters
element
Element
willMutate
privateParameters
trigger
HTMLElement
Returns
void
willNavigate
privateasyncParameters
data
Data<D>|null|undefined
triggeringElement
HTMLElement
Returns
Promise<void>
didMutate
privateReturns
void
onTriggerEvent
privateParameters
event
Event
Returns
void
createRenderRoot
protectedReturns
ShadowRoot|HTMLElement
getVariablesFromInputs
protectedConstructs a variables object from the element’s data-attributes and any slotted variable inputs.Returns
Variables<D, V> | null
isQueryable
privateParameters
node
Node
Returns
node is (ShadowRoot|Document)
getElementByIdFromRoot
privateParameters
id
string|null
Returns
HTMLElement | null
getTemplateFromRoot
privateReturns
HTMLTemplateElement | null
Exports
js ApolloMutationElement
from apollo-mutation.js
custom-element-definition apollo-mutation
from apollo-mutation.js