Controllers: ApolloMutationController
ApolloMutationController
modifies data on your GraphQL server. Pass it a GraphQL mutation document, and any options you choose, and when you call its mutate()
method, it will issue the mutation. It then updates its host when it's state (e.g. data
, error
, or loading
) changes.
The (optional) third argument to the constructor is an ApolloMutationControllerOptions
object, which is the same as the MutationOptions
parameter to mutate()
, as well as onComplete
/onError
callbacks to run your side-effects, if you choose.
Apollo Elements controllers are not limited to Lit. Use them with any object that implements the ReactiveControllerHost
interface. See ControllerHostMixin
for an example.
import '@apollo-elements/components/apollo-client';
import { ApolloMutationController } from '@apollo-elements/core';
import { customElement, state, query } from 'lit/decorators.js';
import { css, html, LitElement } from 'lit';
import { AddUserMutation } from './AddUser.mutation.graphql.js';
import '@material/mwc-button';
import '@material/mwc-textfield';
@customElement('add-user')
class AddUser extends LitElement {
addUser = new ApolloMutationController(this, AddUserMutation);
render() {
return html`
<mwc-textfield label="Add User" value=${this.addUser.data?.addUser?.name}></mwc-textfield>
<mwc-button label="Add" @click="${this.mutate}"></mwc-button>
<p ?hidden="${!this.addUser.data}">${this.addUser.data?.addUser?.name} added!</p>
`;
}
mutate(event) {
const name = this.shadowRoot.querySelector('mwc-textfield').value;
this.addUser.mutate({ variables: { name } });
}
}
<script type="module" src="add-user.js"></script>
<script type="module" src="client.js"></script>
<apollo-client>
<add-user></add-user>
</apollo-client>
import { gql, TypedDocumentNode } from '@apollo/client/core';
type T = TypedDocumentNode<{ addUser: { name: string } }, { name: string }>;
export const AddUserMutation: T = gql`
mutation AddUser($name: String) {
addUser(name: $name) {
name
}
}
`;
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema } from '@graphql-tools/schema';
const USERS = [ ];
const schema = makeExecutableSchema({
typeDefs: `
type User {
id: ID
name: String
}
type Mutation {
addUser(name: String): User
}
type Query {
users: [User]
}
`,
resolvers: {
Query: { users: async () => USERS },
Mutation: {
async addUser(_, { name }) {
const id = Math.max(...USERS.map(x => x.id)) + 1
const user = { id, name }
USERS.push[user]
return user;
}
},
}
});
document.querySelector('apollo-client')
.client = new ApolloClient({
cache: new InMemoryCache(),
link: new SchemaLink({ schema }),
});
Properties
mutation
ComponentDocument<D, V> | null
The GraphQL mutation document
called
inherited from ApolloControllerboolean
client
inherited from ApolloControllerApolloClient<NormalizedCacheObject> | null
The ApolloClient
instance for this controller.
data
inherited from ApolloControllerData<D> | null
Latest data for the operation, or null
.
document
inherited from ApolloControllerComponentDocument<D, V> | null
The GraphQL document for the operation.
error
inherited from ApolloControllerApolloError | null
Latest error from the operation, or null
.
errors
inherited from ApolloControllerreadonly GraphQLError[]
Latest errors from the operation, or []
.
loading
inherited from ApolloControllerboolean
Whether a request is in-flight.
options
inherited from ApolloControllerApolloControllerOptions<D, V>
Options to customize the mutation and to interface with the controller.
Option | Type | Description |
---|---|---|
variables | Variables<D, V> |
Operation variables. See variables. |
optimisticResponse | OptimisticResponseType<D, V> |
See optimisticResponse |
fetchPolicy | ErrorPolicy |
See fetchPolicy |
refetchQueries | RefetchQueriesType<D> | null |
See refetchQueries |
awaitRefetchQueries | boolean |
See awaitRefetchQueries |
update | MutationUpdaterFn<Data<D>> |
Function used to update the client cache following the mutation. See updater. |
Inherits from ApolloControllerOptions
variables
inherited from ApolloControllerVariables<D, V> | null
Variables for the operation.
Methods
mutate
Fires a mutation 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>>>
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 |
hostConnected
inherited from ApolloControllerReturns
void
hostDisconnected
inherited from ApolloControllerReturns
void
Events
Name | Type | Description |
---|---|---|
apollo-controller-connected |
|
The controller's host connected to the DOM. |
apollo-controller-disconnected |
|
The controller's host disconnected from the DOM. |
Private API
Private Properties
mostRecentMutationId
number
The ID number of the most recent mutation since the element was instantiated.
#client
inherited from ApolloControllerApolloClient<NormalizedCacheObject> | null
#document
inherited from ApolloControllerComponentDocument<D, V> | null
#options
inherited from ApolloControllerApolloControllerOptions<D, V>
Option | Type | Description |
---|---|---|
client | ApolloClient<NormalizedCacheObject> |
The ApolloClient instance for the controller. |
variables | Variables<D, V> |
Variables for the operation. |
context | any |
Context passed to the link execution chain. |
errorPolicy | ErrorPolicy |
the error policy for the operation |
hostElement | HTMLElement |
When provided, the controller will fall back to this element to fire events |
emitter
inherited from ApolloControllerEventTarget
The event emitter to use when firing events, usually the host element.
Private Methods
onMutationError
Callback for when a mutation fails.
Parameters
mutationId
number
apolloError
ApolloError
Returns
never
onCompletedMutation
Callback for when a mutation is completed.
Parameters
mutationId
number
response
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 |
Returns
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 |
isMostRecentMutation
Returns true when an ID matches the most recent mutation id.
Parameters
mutationId
number
Returns
boolean
generateMutationId
Increments and returns the most recent mutation id.
Returns
number
clientChanged
inherited from ApolloControllercallback for when the Apollo client changes.
Parameters
client
ApolloClient<NormalizedCacheObject> | null
Returns
void
documentChanged
inherited from ApolloControllercallback for when the GraphQL document changes.
Parameters
document
ComponentDocument<D, V> | null
Returns
void
init
inherited from ApolloControllerAssigns the controller's variables and GraphQL document.
Parameters
document
ComponentDocument<D, V> | null
Returns
void
notify
inherited from ApolloControllerrequests an update on the host with the provided properties.
Parameters
properties
Record<string, unknown>
Returns
void
optionsChanged
inherited from ApolloControllercallback for when the options change.
Parameters
options
ApolloControllerOptions<D, V>
Option | Type | Description |
---|---|---|
client | ApolloClient<NormalizedCacheObject> |
The ApolloClient instance for the controller. |
variables | Variables<D, V> |
Variables for the operation. |
context | any |
Context passed to the link execution chain. |
errorPolicy | ErrorPolicy |
the error policy for the operation |
hostElement | HTMLElement |
When provided, the controller will fall back to this element to fire events |
Returns
void
variablesChanged
inherited from ApolloControllercallback for when the GraphQL variables change.
Parameters
variables
Variables<D, V> | null
Returns
void
Exports
import { ApolloMutationController } from '@apollo-elements/core/apollo-mutation-controller';