How to use GraphQL mutations in React and Apollo Client

Marcin Kwiatkowski /
How to use GraphQL mutations in React and Apollo Client

In one of my previous articles, I described GraphQL queries. Today I would like to show you how to work with GraphQL mutations.

What is a mutation in GraphQL?

A mutation is a function that allows you to modify data. In REST APIs, data is typically fetched by the GET method and added or modified by the POST or PUT method.

In GraphQL, there are two types of operations:

  1. 1. Query: fetching data

  2. 2. Mutation: modifying/adding data

Mutation example

Take a look at the simple mutation from the Magento eCommerce platform's GraphQL API that creates an empty cart:

1mutation {
2  createEmptyCart(input: {})
3}

Mutation receives an empty input object and returns a token of the newly created cart:

Magento GraphQL API createEmptyCart mutation

Let's try something more complicated - a mutation that takes some input via variables:

1
2mutation {
3  addSimpleProductsToCart(input: { cart_id: "B06YCRcXAaOHGTtZ2Iij8SDHAq0AR49F", cart_items: [{ data:{sku: "24-MB01", quantity: 1} }] }) {
4    cart {
5      total_quantity
6      items {
7        product {
8          name
9        }
10      }
11    }
12  }
13}

In this example, you can see the addSimpleProductsToCart mutation that takes an input object with the following variables:

  • cart_id: Cart ID to which the product will be added

  • cart_items: array of objects that contains the SKU of the product and its quantity. The example above adds one product of SKU 24-MB01 to the cart with ID B06YCRcXAaOHGTtZ2Iij8SDHAq0AR49F

Mutation returns the cart object, and in this example, I requested total_quantity of the cart and information about the cart items' names.

The response to that GraphQL mutation looks like this:

1{
2  "data": {
3    "addSimpleProductsToCart": {
4      "cart": {
5        "total_quantity": 1,
6        "items": [
7          {
8            "product": {
9              "name": "Joust Duffle Bag"
10            }
11          }
12        ]
13      }
14    }
15  }
16}

Hard-coding variables is not a good idea in real projects, so take a look at an example where I pass variables by arguments:

1mutation addSimpleProductsToCart($input: AddSimpleProductsToCartInput ) {
2  addSimpleProductsToCart(input: $input) {
3    cart {
4      total_quantity
5      items {
6        product {
7          name
8        }
9      }
10    }
11  }
12}

In this case, you can pass variables as an object:

1{
2  "input": {
3    "cart_id": "B06YCRcXAaOHGTtZ2Iij8SDHAq0AR49F",
4    "cart_items": [
5      {
6        "data": {
7          "sku": "24-MB01",
8          "quantity": 1
9        }
10      }
11    ]
12  }
13}

Mutation returns a similar response as the previous one :

graphql variables in type mutation

Apollo Client

Apollo Client is one of the most popular GraphQL clients for React, and in this article, I want to show you how to work with mutations using Apollo Client and React.

Prerequisites

If you want to run the examples below on your computer, you should:

  1. 1. Set app a new React App using create-react-app

  2. 2. Initialize Apollo Client (note: I used Magento GraphQL API in examples, but it is up to you which API you would like to use)

Execute mutation in Apollo client

Apollo Client offers predefined hooks to execute GraphQL queries and mutations. These hooks offer much more than only sending requests and receiving responses. Let's go dive to see what the useMutation hook provides.

The useMutation hook

Let's see how the useMutation hook works with a real example. To do so, I use the createEmptyCart mutation. First, I need to define that mutation in the code:

1import { gql, useMutation } from '@apollo/client';
2
3const CREATE_EMPTY_CART = gql`
4  mutation {
5    createEmptyCart(input: {})
6  }
7`;

That GraphQL operation takes no arguments so executing is very simple and looks like this:

1useMutation(CREATE_EMPTY_CART)

Full example:

1import { gql, useMutation } from '@apollo/client';
2
3const CREATE_EMPTY_CART = gql`
4  mutation {
5    createEmptyCart(input: {})
6  }
7`;
8
9function App() {
10  const [mutateFunction, { data, loading, error, called, reset }] = useMutation(CREATE_EMPTY_CART);
11
12  if (loading) {
13    return <>Loading...</>
14  }
15
16  return <main style={{padding: '10px'}}>
17    <h1>GraphQL mutations tutorial</h1>
18    <button type="button" onClick={() => mutateFunction()}>Create cart</button>
19
20    <div>
21      <h2>Data: </h2>
22      {data && data.createEmptyCart}
23    </div>
24    {error && <div>
25      <h2>Error:</h2>
26      {error.toString()}
27    </div>}
28    <div>
29      <h2>Called: {called.toString()}</h2>
30      <button type="button" onClick={() => reset()}>Reset</button>
31    </div>
32  </main>
33}
34
35export default App;

This part of the code:

1const [mutateFunction, { data, loading, error }] = useMutation(CREATE_EMPTY_CART); 

is responsible for initializing the useMutation hook in the component

Mutation response

The useMutation hook returns an array that contains mutate function and an object with some properties.

mutate Function

A function that must be called to execute mutation. This example is named as mutateFunction, but you can name it what you want for example, you can use the operation name: createEmptyCart, or whatever you want.

The code below is responsible for executing mutation:

1<button type="button" onClick={() => mutateFunction()}>Create cart</button>

Basically, there is a button that has bounded the mutate function on the click event. So when the user clicks that button, the mutation will be executed.

data

The data fields contain the mutation response. Then you can use this data in the component. In this example, I display the mutation response on the screen:

1<div>
2  <h2>Data: </h2>
3  {data && data.createEmptyCart}
4</div>

LOADING

The loading fields show the state of the mutation. If it's true, that means that mutation is in progress and fetches data at the moment. When mutation returns value and execution is finished, the loading field equals false.

In this example, I use the loading field only to display the loading information on the screen:

1if (loading) {
2    return <>Loading...</>
3}

error

When mutation meets some errors on the backend side, they will be returned here. The error object can contain either an array of graphQLErrors objects or one single networkError object. If GraphQL server doesn't produce any error, the error object is undefined.

In my example, I display potential errors on the screen:

1{error && <div>
2  <h2>Error:</h2>
3  {error.toString()}
4</div>}

called

The called is a flag that describes if mutate function is called or not.

Reset

When you want to rest the mutation state to initial, you call the reset() function. That means Apolo will restore all fields returned by the useMutation hook. to default values.

Mutation options

The previous example was straightforward. I didn't even pass any variables there. Let's see something more sophisticated. To pass additional parameters to the useMutation hook, you must pass an object as a second argument to the operation.

1const [mutateFunction, { data, loading, error, called, reset }] = useMutation(MUTATION_STRING, { 
2   // additional options here
3});

Note: MUTATION_STRING is a GraphQL query string parsed with the gql template literal.

Variables

The variables object allows passing GraphQL variables to the mutation. Each key in this object represents one variable.

1const CREATE_EMPTY_CART = gql`
2   mutation createCart($input: createEmptyCartInput) {
3    createEmptyCart(input: $input)
4  }
5`;
6
7function App() {
8  const [mutateFunction, { data, loading, error, called, reset }] = useMutation(CREATE_EMPTY_CART, {
9    variables: {
10      input: {
11        cart_id: 'lTO8UjTglq5djnpIOseLN7RWvpvwSRba'
12      }
13    }
14  });
15
16 (...) // rest of the code

I updated the mutation string, and from now it accepts one argument: $input object:

1mutation createCart($input: createEmptyCartInput) {
2    createEmptyCart(input: $input)
3}

Then I passed the variables object to the useMutation hook:

1const [mutateFunction, { data, loading, error, called, reset }] = useMutation(CREATE_EMPTY_CART, {
2    variables: {
3        input: {
4            cart_id: 'lTO8UjTglq5djnpIOseLN7RWvpvwSRba'
5        }
6    }
7});

This code creates a new cart with the ID I specified in the variables:

graphql mutation results

errorPolicy

The errorPolicy field allows specifying how the hook handles errors.

Possible values:

  • None (default value) - if the response contains errors, they are returned on the error object, and data is undefined.

  • Ignore - errors are skipped, so the error object is not populated even if something goes wrong.

  • All - two objects: data and error, are populated. This is useful if you want to settle partial data even if something went wrong during the mutation execution.

Take a look at the example with the default error policy:

graphql service throws error

onCompleted

The onCompleted is a callback function called when the mutation was executed without errors. In this function, you can access mutation results and options passed to the mutation. Take a look at the example:

1import {gql, useMutation} from "@apollo/client";
2
3const ADD_PRODUCT_TO_CART = gql`
4  mutation AddProductsToCart($cartId: String!, $cartItems: [CartItemInput!]!) {
5     addProductsToCart(cartId: $cartId, cartItems: $cartItems) {
6      cart {
7        id
8        items {
9          quantity
10          prices {
11            row_total {
12              currency
13              value
14            }
15          }
16        }
17        prices {
18          grand_total {
19            currency
20            value
21          }
22        }
23        total_quantity
24      }
25    }
26  }
27`;
28
29const [addProductToCart] = useMutation(ADD_PRODUCT_TO_CART, {
30    variables: {
31        cartId: 'koESgYi6WU5BiCJDRkgfilDB4z1IsfHV',
32        cartItems: [
33            {
34                selected_options: ['Y29uZmlndXJhYmxlLzE0NC8yMTU'],
35                quantity: 1,
36                sku: "GC-747-SOCK"
37            }
38        ]
39    },
40    onCompleted: (data, options) => {
41        console.log(data, options)
42    }
43});
44
45// (...) 
46<button type="button" onClick={() => addProductToCart()}>Add product to cart</button>

In this example, the onCompleted function prints data and options to the console:

mutation fetch data

onError

The onError is a callback function called when a mutation returns some error. In this function, you can access the error object and options passed to the mutation.

Updating the cache

Apollo client has its own caching system and, by default, writes data to the cache. The cache impacts the speed of operation, because some operations can retrieve data only from the cache or first from the cache and then from the server.

In addition, a technique called optimistic responses can be used in working with mutations. Let me explain this to you with an example:

  1. 1. The user enters the website

  2. 2. Apollo downloads a list of products and displays them on the screen

  3. 3. The user adds a product to the basket

  4. 4. Storefront needs to update the shopping cart details.

After executing the mutation, we have two to accomplish this:

  1. 1. Update the cart data in the cache

  2. 2. Perform the shopping cart inquiry again

Let's see how to implement this in Apollo.

How Apollo Updates the cache

First, let's create a new query that fetches the cart:

1const GET_CART = gql`
2  query getCart {
3    cart(cart_id: "koESgYi6WU5BiCJDRkgfilDB4z1IsfHV") {
4      id
5      items {
6        quantity
7        prices {
8          row_total {
9            currency
10            value
11          }
12        }
13      }
14      prices {
15        grand_total {
16          currency
17          value
18        }
19      }
20      total_quantity
21    }
22  }
23`;

Second, use the useLazyQuery hook to execute the query:

1const [getCart] = useLazyQuery(GET_CART, {
2    onCompleted: (data) => {
3      console.log('cart data: ', data)
4    }
5  });

Third, add a button and bind the getCart function to the onClick event of that button:

1<button type="button" onClick={() => getCart()}>Get cart</button>

When the user clicks that button, the query is executed and the onCompleted callback prints cart data to the console:

server side data of graphql operation printed in the console

At the same time, Apollo writes data of that cart to the cache:

following query saved in the cache

Now, when the user clicks Add Product to cart button, Apollo runs the addProductToCart mutation, and the product will be added to the cart on the server side. Under the hood, Apollo updates the cart data in the cache.

Updating cache manually

In some cases, Apollo is not able to update the cache automatically. Then you can define your own update function and write to the cache manually. You can pass an update function as a field of the settings object that useMutation hook receives:

1import {gql, useMutation} from "@apollo/client";
2
3const [addProductToCart] = useMutation(ADD_PRODUCT_TO_CART, {
4    // (...)
5    update(cache, {data: {addProductsToCart}}) {
6        cache.modify({
7            fields: {
8                cart(existingCartRef = {}) {
9                    const newCartRef = cache.writeFragment({
10                        data: addProductsToCart.cart,
11                        fragment: gql`
12                            fragment NewCart on Cart {
13                              id
14                              items {
15                                quantity
16                                prices {
17                                  row_total {
18                                    currency
19                                    value
20                                  }
21                                }
22                              }
23                              prices {
24                                grand_total {
25                                  currency
26                                  value
27                                }
28                              }
29                              total_quantity
30                            }
31                          `
32                    });
33                    return {...existingCartRef, newCartRef};
34                }
35            }
36        });
37    }
38});

The update function receives the cache object and data returned by the mutation:

the modify method is available on the cache object

On the cache object, there is the modify function that allows updating the cache. In that function, I create a new cart fragment that contains data returned from mutation, and at the end, I return the merged cache cart with a new cart. Then Apollo updates the cache.

refetchQueries

Another mechanism to update the state after mutation execution is refetching queries. You can specify which queries should be executed by passing them to the refetchQueries array.

1const [addProductToCart] = useMutation(ADD_PRODUCT_TO_CART, {
2    // (...)
3    refetchQueries: [
4        'getCart'
5    ]
6});

the "getCart" is the query defined earlier:

1const GET_CART = gql`
2  query getCart {
3     // (...)
4  }
5`;

Alternatively, you can pass the query as an object like this:

1const GET_CART = gql`
2  query getCart {
3     // (...)
4  }
5`;
6
7// (...)
8
9const [addProductToCart] = useMutation(ADD_PRODUCT_TO_CART, {   
10    // (...) 
11    refetchQueries: [
12        { query: GET_CART}
13    ]
14});

Optimistic responses

When you perform graphql mutations, they modify server-side data, which can take some time. You would have new data as fast as possible and display it to the user. Apollo provides an interesting mechanism: Optimistic mutation results, and thanks to this feature, you can update your UI before your server responds. Take a look at how it works:

1const [addProductToCart] = useMutation(ADD_PRODUCT_TO_CART, {
2    // (...)
3    optimisticResponse: {
4        addProductsToCart: {
5            cart: {
6                id: 'koESgYi6WU5BiCJDRkgfilDB4z1IsfHV',
7                __typename: "Cart",
8                total_quantity: 40
9                // other cart fields
10            }
11        }
12    }
13});

The optimisticResponse object takes an object with the same structure as the expected mutation response. When the mutate function is called, UI will be updated. Finally, when a request is done, Apollo replaces the fake data you specified with real server side data.

Conclusion

Mutations next to queries are the core of Apollo Client's API. Sending a request and receiving a response is not all that Apollo Client offers. Thanks to the fact that Apollo has its state, developers can reliably program communication with the API and provide users with a very good UX. One of the most interesting features is optimistic responses, thanks to which the UI will seem fast even when the server is slow.

Share this article with your friends!

Each share supports and motivates me to create new content. Thank you!

About the author

Marcin Kwiatkowski

Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.

Read more