Components: apollo-mutation
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>
mutation InsertUser($name: String!) {
insert_users(objects: {name: $name}) {
returning {
name
id
timestamp
}
}
}
[hidden] { display: none !important; }
import '@apollo-elements/components';
import '@power-elements/card';
import '@material/mwc-button';
import '@material/mwc-textfield';
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
Examples
Using data attributes
<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"
}
Using data attributes and variables
<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"
}
Using data attributes and variables with input property
<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"
}
}
Using DOM properties
<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"
}
Attributes
'no-shadow'
inherited from ApolloElementBoolean|string
- When set, the element will render to a
<div>
in its light DOM. If set with a string, the string will be the div's class name.
Properties
is
(read-only)string
variables
Variables<D, V> | null
Mutation variables.
An object that maps from the name of a variable as used in the mutation GraphQL document to that variable's value.
refetchQueries
refetch-queriesRefetchQueriesType<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.
optimisticResponse
OptimisticResponseType<D, V>
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.
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,
},
});
mutation
null | ComponentDocument<D>
The mutation.
inputKey
input-keystring|null
key to wrap variables in e.g. input
.
When set, variable data attributes will be packed into an object property with the name of this property
ignoreResults
ignore-resultsboolean
If true, the returned data property will not update with the mutation result.
fetchPolicy
fetch-policy'no-cache'
Specifies the FetchPolicy to be used for this mutation.
errorPolicy
error-policyErrorPolicy
Specifies the ErrorPolicy to be used for this mutation.
debounce
debouncenumber | null
Optional number of milliseconds to wait between calls
controller
ApolloMutationController<D, V>
context
Record<string, unknown>
Context passed to the link execution chain.
called
calledboolean
Whether the mutation was called
awaitRefetchQueries
await-refetch-queriesboolean
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.
client
inherited from ApolloElementApolloClient<NormalizedCacheObject> | null
The Apollo Client instance.
data
inherited from ApolloElementData<D> | null
Latest Data.
document
inherited from ApolloElementComponentDocument<D> | null
Operation document.
GraphQL operation document i.e. query, subscription, or mutation.
Must be a parsed GraphQL DocumentNode
error
inherited from ApolloElementError | ApolloError | null
Latest error
errors
inherited from ApolloElementreadonly GraphQLError[]
Latest errors
loading
inherited from ApolloElement loadingboolean
Whether a request is in flight.
readyToReceiveDocument
inherited from ApolloElementboolean
template
inherited from ApolloElement templateHTMLTemplateElement | null
Template element to render. Can either be a light-DOM child of the element,
or referenced by ID with the template
attribute.
templateHandlers
inherited from ApolloElementTemplateHandlers
Methods
updater
A 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>>>
Returns
ReturnType<MutationUpdaterFn<Data<D>>>
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.
Parameters
data
Data<D>
mutation data
trigger
HTMLElement
the trigger element which triggered this mutation
Returns
mutate
Parameters
params
Partial<MutationOptions<Data<D>, Variables<D, V>>> | undefined
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`{lang=ts} |
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 |
$
inherited from ApolloElementquerySelector
within the render root.
Parameters
selector
string
Returns
E | null
$$
inherited from ApolloElementquerySelectorAll
within the render root.
Parameters
selector
string
Returns
NodeListOf<E>
Slots
Mutations
Events
Name | Type | Description |
---|---|---|
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. . |
will-mutate |
|
When the element is about to mutate. Useful for setting variables. Prevent default to prevent mutation. Detail is |
mutation-error |
|
When the mutation is rejected. |
mutation-completed |
|
When the mutation resolves. |
apollo-element-disconnected |
|
when the element disconnects from the dom |
apollo-element-connected |
|
when the element connects to the dom |
|
Private API
Private Properties
triggers
NodeListOf<HTMLElement>
Slotted trigger nodes
inputs
InputLikeElement[]
Variable input nodes
inFlightTrigger
HTMLElement | null
doMutate
debouncedMutate
this
buttons
ButtonLikeElement[]
If the slotted trigger node is a button, the trigger If the slotted trigger node is a link with a button as it's first child, the button
#listeners
#buttonMO
MutationObserver
Private Methods
toVariables
Parameters
acc
T
element
InputLikeElement
Returns
T
isTriggerNode
Parameters
node
Node
Returns
node is HTMLElement
isLink
Parameters
node
Element|null
Returns
node is HTMLAnchorElement
isButton
False when the element is a link.
Parameters
node
Element|null
Returns
node is ButtonLikeElement
debounce
Parameters
f
() => void
timeout
number
Returns
() => void
isQueryable
inherited from ApolloElementParameters
node
Node
Returns
node is (ShadowRoot|Document)
willNavigate
Parameters
data
Data<D>|null|undefined
triggeringElement
HTMLElement
Returns
Promise<void>
willMutate
Parameters
trigger
HTMLElement
Returns
void
onTriggerEvent
Parameters
event
Event
Returns
void
onSlotchange
Returns
void
onLightDomMutation
Parameters
records
MutationRecord[]
getVariablesFromInputs
Constructs a variables object from the element's data-attributes and any slotted variable inputs.
Returns
Variables<D, V> | null
didMutate
Returns
void
createRenderRoot
Returns
ShadowRoot|HTMLElement
addTriggerListener
Parameters
element
HTMLElement
getElementByIdFromRoot
inherited from ApolloElementParameters
id
string|null
Returns
HTMLElement | null
getTemplateFromRoot
inherited from ApolloElementReturns
HTMLTemplateElement | null
Exports
import '@apollo-elements/components/apollo-mutation';
import {
WillMutateError, ApolloMutationElement} from '@apollo-elements/components/apollo-mutation';