In this tutorial, we will delve into performing mutations with Apollo Client, a comprehensive state management library for JavaScript applications. Our goal is to enable you to modify data on your GraphQL server through the use of mutations.
By the end of this tutorial, you will learn how to:
Before you start, you should have:
In GraphQL, mutations are responsible for creating, updating, and deleting data. To achieve these operations, we need to write mutation queries and use Apollo Client to execute these queries.
Let's define a CREATE_USER
mutation. The gql
tag parses our string literal into a GraphQL Document.
import { gql } from '@apollo/client';
const CREATE_USER = gql`
mutation CreateUser($name: String!) {
createUser(name: $name) {
id
name
}
}
`;
In this mutation, we are creating a user and passing a name
variable of type String
. The server then returns the id
and name
of the new user.
To use this mutation in our React component, we use the useMutation
hook from the @apollo/client
package. This hook returns a mutate function (createUser
in our case) that we can call at any point to execute the mutation.
import { useMutation } from '@apollo/client';
function App() {
const [createUser] = useMutation(CREATE_USER);
return (
// JSX here
);
}
Calling the mutate function:
createUser({ variables: { name: 'John Doe' } });
Here's a full example of creating a user:
import React from 'react';
import { gql, useMutation } from '@apollo/client';
// Define the mutation
const CREATE_USER = gql`
mutation CreateUser($name: String!) {
createUser(name: $name) {
id
name
}
}
`;
// Component definition
function App() {
// Hook to get the mutation function
const [createUser, { data }] = useMutation(CREATE_USER);
// Execute the mutation when a button is clicked
return (
<button onClick={() => createUser({ variables: { name: 'John Doe' } })}>
Create User
</button>
);
}
export default App;
When the Create User
button is clicked, a new user named John Doe
is created.
Here's how to update a user's name:
import React from 'react';
import { gql, useMutation } from '@apollo/client';
// Define the mutation
const UPDATE_USER = gql`
mutation UpdateUser($id: ID!, $name: String!) {
updateUser(id: $id, name: $name) {
id
name
}
}
`;
// Component definition
function App() {
// Hook to get the mutation function
const [updateUser, { data }] = useMutation(UPDATE_USER);
// Execute the mutation when a button is clicked
return (
<button onClick={() => updateUser({ variables: { id: '1', name: 'Jane Doe' } })}>
Update User
</button>
);
}
export default App;
In this example, when we click the Update User
button, the user with an id of 1
will have their name updated to Jane Doe
.
In this tutorial, we have covered:
Next, you can try to implement deleting data using mutations. Once you're comfortable with mutations, you can explore more advanced topics such as caching and optimistic UI updates with Apollo Client.
Happy coding!