GraphQL / GraphQL with Apollo Client
Using Apollo for Mutations and Updates
This tutorial delves into performing mutations with Apollo Client, allowing you to modify data on your GraphQL server. Learn how to create, update, and delete data with GraphQL mu…
Section overview
5 resourcesExplains how to consume GraphQL APIs using Apollo Client.
Using Apollo for Mutations and Updates
1. Introduction
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:
- Understand and use GraphQL mutations
- Create, update, and delete data with Apollo Client
Prerequisites
Before you start, you should have:
- Basic knowledge of JavaScript and React
- Familiarity with GraphQL and Apollo Client
- A running GraphQL server and Apollo Client setup
2. Step-by-Step Guide
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.
Writing a Mutation
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.
Using the Mutation
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' } });
3. Code Examples
Example 1: Creating a User
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.
Example 2: Updating a User
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.
4. Summary
In this tutorial, we have covered:
- How to write and use GraphQL mutations with Apollo Client
- How to create and update data on a GraphQL server
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.
5. Practice Exercises
- Write a mutation to delete a user and use it in a React component.
- Write a mutation to create a post with a title and content, and use it in a React component.
- Update the user creation example to also include an email field.
Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article