Manually update Apollo cache after GraphQL mutation

Manually update Apollo cache after GraphQL mutation
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.
Elixir Newsletter
Expand your skills

Download free e-books, watch expert tech talks, and explore open-source projects. Everything you need to grow as a developer - completely free.

Table of contents

Ensuring that GraphQL mutations properly update your Apollo client's cache can be a bit tricky - here's how to manually control that.

Unless a mutation mutates a <a href="https://www.apollographql.com/docs/react/data/mutations/#updating-the-cache-after-a-mutation" target="_blank">single existing entity</a>, you'll need to use a specific update function to ensure data updates returned by the mutation are propagated.

Your call to the <a href="https://www.apollographql.com/docs/react/api/react-hooks/#usemutation" target="_blank">useMutation hook</a> can take an update callback function, which takes two arguments: a DataProxy object allowing you to interact with Apollo's cache store, and a FetchResult object containing data returned by the mutation.

The DataProxy object can be interacted with using readQuery and writeData methods to read existing cache data and update entries, respectively.

// This mutation is something that does not represent an existing entity,
// note that no ID is returned.
const SOME_MUTATION = gql`
  mutation ($something: String!) {
    foo (something: $something) {
      result
      info
      bar {
        id
        one
        two
      }
    }
  }
`;

const BAR_QUERY = gql`
  query ($id: ID!) {
    bar (id: $id) {
      id
      one
      two
    }
  }
`;

function Foobar() {
  const [mutate, { data }] = useMutation(SOME_MUTATION);

  // Run the mutation at component mount
  useEffect(
    () => {
      mutate({
        variables: { something: 'something' },
        update: (store, { data: { foo: { bar } } }) {
          store.writeQuery({
            query: BAR_QUERY,
            data: { bar },
            variables: { id: bar.id }
          })
        }
      })
    }
  )

  return <div>{data && JSON.stringify(data)}</div>;
}

When you then execute BAR_QUERY with <a href="https://www.apollographql.com/docs/react/api/react-hoc/#optionsfetchpolicy" target="_blank">any of the fetchPolicy options that involve reading from cache</a>, you'll find that the cache will work.

Note that it could often be a better idea to think about how to remodel the resource so that it can have an id field returned by the API, or configuring the cache with a <a href="https://www.apollographql.com/docs/react/caching/cache-configuration/#custom-identifiers" target="_blank">dataIdFromObject</a> function to infer an ID from the type so that it can be treated as something cacheable. Nonetheless, it's good to keep the writeQuery solution in mind, as you don't always have control over the API you need to consume.

Work with a team that keeps learning and building better software every day.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

How to revert commit in Git

Did you ever create a commit that you wish never happened? Let's be honest - we all did. There is an easy way to revert it in Git.

How to Lazy-Load external scripts for better page speed?

Nowadays, with an ever-growing number of web services, we tend to overload Web apps with external resources. As a result, it decreases page load speed and affects SEO score. There is a pretty easy solution for that.

How to check if a set contains exact values with Jest in JS?

TLDR: With jest-extended package you can write: expect([...set]).toIncludeSameMembers([value1, value2]);. If you are looking to a native, but longer solution scroll down a bit.