Using Apollo for Mutations and Updates

Tutorial 3 of 5

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!