0
0
GraphqlHow-ToBeginner · 4 min read

How to Update Cache After Mutation in GraphQL

After performing a mutation in GraphQL, update the cache by using the update function or refetchQueries option provided by your GraphQL client. This ensures your UI shows the latest data without waiting for a full reload.
📐

Syntax

Use the update function inside your mutation call to modify the cache directly. Alternatively, use refetchQueries to reload specific queries after the mutation.

  • update(cache, { data }): Function to update cache manually.
  • refetchQueries: ["QueryName"]: Array of queries to refetch after mutation.
graphql
mutationFunction({
  variables: { id: 1 },
  update(cache, { data: { updateItem } }) {
    cache.modify({
      fields: {
        items(existingItems = []) {
          const updatedItemRef = cache.writeFragment({
            data: updateItem,
            fragment: gql`fragment NewItem on Item { id name }`
          });
          return [...existingItems, updatedItemRef];
        }
      }
    });
  },
  refetchQueries: ["GetItems"]
});
💻

Example

This example shows how to update the Apollo Client cache after adding a new item with a mutation. It modifies the cache to include the new item without refetching all data.

javascript
import { gql, useMutation } from '@apollo/client';

const ADD_ITEM = gql`
  mutation AddItem($name: String!) {
    addItem(name: $name) {
      id
      name
    }
  }
`;

const GET_ITEMS = gql`
  query GetItems {
    items {
      id
      name
    }
  }
`;

function AddItemComponent() {
  const [addItem] = useMutation(ADD_ITEM, {
    update(cache, { data: { addItem } }) {
      cache.modify({
        fields: {
          items(existingItems = []) {
            const newItemRef = cache.writeFragment({
              data: addItem,
              fragment: gql`fragment NewItem on Item { id name }`
            });
            return [...existingItems, newItemRef];
          }
        }
      });
    }
  });

  return (
    <button onClick={() => addItem({ variables: { name: "New Item" } })}>
      Add Item
    </button>
  );
}
Output
UI updates immediately to show the new item in the list without refetching the entire query.
⚠️

Common Pitfalls

Common mistakes include not updating the cache correctly, which causes the UI to not reflect changes immediately. Another mistake is forgetting to write fragments when modifying cache, leading to errors.

Also, relying only on refetchQueries can cause unnecessary network requests and slower UI updates.

javascript
/* Wrong way: Not updating cache */
useMutation(ADD_ITEM);

/* Right way: Update cache manually */
useMutation(ADD_ITEM, {
  update(cache, { data: { addItem } }) {
    cache.modify({
      fields: {
        items(existingItems = []) {
          const newItemRef = cache.writeFragment({
            data: addItem,
            fragment: gql`fragment NewItem on Item { id name }`
          });
          return [...existingItems, newItemRef];
        }
      }
    });
  }
});
📊

Quick Reference

  • update(cache, { data }): Modify cache directly after mutation.
  • cache.modify(): Change specific fields in cache.
  • cache.writeFragment(): Write new data fragment to cache.
  • refetchQueries: Refetch queries to update cache but less efficient.

Key Takeaways

Always update the cache after a mutation to keep UI data fresh.
Use the update function with cache.modify and cache.writeFragment for precise cache updates.
Avoid unnecessary network requests by preferring cache updates over refetchQueries.
Write fragments when modifying cache to prevent errors.
Test cache updates to ensure UI reflects changes immediately.