Manually update Apollo cache after GraphQL mutation

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 single existing entity, you'll need to use a specific update function to ensure data updates returned by the mutation are propagated.

Your call to the useMutation hook 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 any of the fetchPolicy options that involve reading from cache, 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 dataIdFromObject 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.

A girl receiving new message

Sign to our Newsletter

We're committed to your privacy. Curiosum uses the information you provide to us to contact you about our relevant content. You may unsubscribe from these communications at any time. For more information, check out our privacy policy.

Michał Buszkiewicz, Elixir Developer
Michał Buszkiewicz Curiosum Founder & CTO

Read more
on #curiosum blog

Phoenix LiveView Tutorial: Adding Phoenix PubSub and Pow Authentication to Messenger
  • Elixir

Phoenix LiveView Tutorial: Adding Phoenix PubSub and Pow Authentication to Messenger

We've already bootstrapped our Phoenix LiveView-based Messenger app's database structure and a first LiveView page.

This time, we're going to improve real-time communication between the app's users using Phoenix PubSub, and use the Pow library to add secure user authentication.

As of November 2020, the latest Phoenix LiveView version is 0.14.8 - and the series has been updated to match it!

5 top-tier companies that use Elixir
  • Elixir

5 top-tier companies that use Elixir

Elixir is a pretty capable language - and it consistently ranks near the top of most loved and wanted languages rankings. It has a large following and some very persuasive preachers as well. But that would not be enough to make me like it – what I need as real proof of its strengths is real businesses that strive with Elixir.

That’s what this list is all about – a bunch of stories from top companies that chose Elixir and never looked back. Let us show you how its power and versatility shows in practice.