useMutation
Apollo Client API reference
Refer to the Mutations section for a more in-depth overview of
useMutation.
Example
1 import { gql, useMutation } from "@apollo/client";
2
3 const ADD_TODO = gql`
4 mutation AddTodo($type: String!) {
5 addTodo(type: $type) {
6 id
7 type
8 }
9 }
10 `;
11
12 function AddTodo() {
13 let input;
14 const [addTodo, { data }] = useMutation(ADD_TODO);
15
16 return (
17 <div>
18 <form
19 onSubmit={(e) => {
20 e.preventDefault();
21 addTodo({ variables: { type: input.value } });
22 input.value = "";
23 }}
24 >
25 <input
26 ref={(node) => {
27 input = node;
28 }}
29 />
30 <button type="submit">Add Todo</button>
31 </form>
32 </div>
33 );
34 }Signature
1useMutation<TData, TVariables, TCache, TConfiguredVariables>(
2 mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: useMutation.Options<NoInfer<TData>, NoInfer<TVariables>, TCache, {
4 [K in keyof TConfiguredVariables]: K extends keyof TVariables ? TConfiguredVariables[K] : never;
5}>
6): useMutation.ResultTuple<TData, MakeRequiredVariablesOptional<TVariables, TConfiguredVariables>, TCache>Parameters
A GraphQL mutation document parsed into an AST by gql.
options (optional)useMutation.Options<NoInfer<TData>, NoInfer<TVariables>, TCache, {
[K in keyof TConfiguredVariables]: K extends keyof TVariables ? TConfiguredVariables[K] : never;
}>Options to control how the mutation is executed.
Show/hide child attributes
If true, makes sure all queries included in refetchQueries are completed before the mutation is considered complete.
The default value is false (queries are refetched asynchronously).
ErrorPolicySpecifies how the mutation handles a response that returns both GraphQL errors and partial results.
For details, see GraphQL error policies.
The default value is none, meaning that the mutation result includes error details but not partial results.
(data: MaybeMasked<TData>, clientOptions?: Options<TData, TVariables, TCache>) => voidA callback function that's called when your mutation successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).
This function is passed the mutation's result data and any options passed to the mutation.
(error: ErrorLike, clientOptions?: Options<TData, TVariables, TCache>) => voidA callback function that's called when the mutation encounters one or more errors (unless errorPolicy is ignore).
This function is passed an ApolloError object that contains either a networkError object or a graphQLErrors array, depending on the error(s) that occurred, as well as any options passed the mutation.
OnQueryUpdated<any>Optional callback for intercepting queries whose cache data has been updated by the mutation, as well as any queries specified in the refetchQueries: [...] list passed to client.mutate.
Returning a Promise from onQueryUpdated will cause the final mutation Promise to await the returned Promise. Returning false causes the query to be ignored.
((result: NormalizedExecutionResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesIncludeAn array (or a function that returns an array) that specifies which queries you want to refetch after the mutation occurs.
Each array value can be either:
An object containing the
queryto execute, along with anyvariablesA string indicating the operation name of the query to refetch
Partial<TVariables> & TConfiguredVariablesAn object containing all of the GraphQL variables your mutation requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
ApolloClientThe instance of ApolloClient to use to execute the mutation.
By default, the instance that's passed down via context is used, but you can provide a different instance here.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
If true, the in-progress mutation's associated component re-renders whenever the network status changes or a network error occurs.
The default value is true.
MutationFetchPolicyProvide no-cache if the mutation's result should not be written to the Apollo Client cache.
The default value is network-only (which means the result is written to the cache).
Unlike queries, mutations do not support fetch policies besides network-only and no-cache.
Unmasked<NoInfer<TData>> | ((vars: TVariables, { IGNORE }: {
IGNORE: IgnoreModifier;
}) => Unmasked<NoInfer<TData>> | IgnoreModifier)By providing either an object or a callback function that, when invoked after
a mutation, allows you to return optimistic data and optionally skip updates
via the IGNORE sentinel object, Apollo Client caches this temporary
(and potentially incorrect) response until the mutation completes, enabling
more responsive UI updates.
For more information, see Optimistic mutation results.
MutationUpdaterFunction<TData, TVariables, TCache>A function used to update the Apollo Client cache after the mutation completes.
For more information, see Updating the cache after a mutation.
booleanTo avoid retaining sensitive information from mutation root field
arguments, Apollo Client v3.4+ automatically clears any ROOT_MUTATION
fields from the cache after each mutation finishes. If you need this
information to remain in the cache, you can prevent the removal by passing
keepRootFields: true to the mutation. ROOT_MUTATION result data are
also passed to the mutation update function, so we recommend obtaining
the results that way, rather than using this option, if possible.
MutationQueryReducersMap<TData>A MutationQueryReducersMap, which is map from query names to
mutation query reducers. Briefly, this map defines how to incorporate the
results of the mutation into the results of queries that are currently
being watched by your application.
Result
1[
2 mutate: (options?: MutationFunctionOptions<TData, TVariables>) => Promise<FetchResult<TData>>,
3 result: MutationResult<TData>
4]mutate(
options?: MutationFunctionOptions<TData, TVariables>
) => Promise<FetchResult<TData>>awaitRefetchQueriescontextfetchPolicyonCompletedonErroroptimisticResponserefetchQueriesonQueryUpdatedupdatevariablesclient
useMutation.The mutate function returns a promise that fulfills with your mutation result.resultMutationResult<TData>Show/hide child attributes
booleanIf true, the mutation's mutate function has been called.
ApolloClientThe instance of Apollo Client that executed the mutation.
Can be useful for manually executing followup operations or writing data to the cache.
MaybeMasked<TData> | null | undefinedThe data returned from your mutation. Can be undefined if the errorPolicy
is all or ignore and the server returns a GraphQL response with errors
but not data or a network error is returned.
ErrorLike | undefinedIf the mutation produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.
For more information, see Handling operation errors.
booleanIf true, the mutation is currently in flight.
() => voidA function that you can call to reset the mutation's result to its initial, uncalled state.