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…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains 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

  1. Write a mutation to delete a user and use it in a React component.
  2. Write a mutation to create a post with a title and content, and use it in a React component.
  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help