Update caches for many queries after one mutation


Disclaimer: I’m new to GraphQL so I’m looking for advice from experts. :blush:

In my React application, I do the following:

  • Retrieve some variations of a Person object all over the application, through slightly different queries.
  • The object always contains a list of Tags
  • In one component, I create a new Tag and apply it via a mutation to a specific Person. Now the Person, in the back-end contains an extra tag in its Tags list.

In details:

  • Home page: queryPersonsWithSomeTags
  • Home page: queryAllTags
  • Person page: queryPersonWithAllTags
  • Another page: queryTagsThatBelongsToListOfPersons
  • Another page: mutationCreateTag
  • Another page: mutationApplyTagToListOfPersons

InAnother page, I use the mutation’s mutationApplyTagToListOfPersons “update” function to update Apollo’s cache but that is not scalable as I need to update the cache of every single query that returned the tag object.

Is updating the cache of various queries expected or it is most likely a misuse of the library or a mis-design of the application/queries where this case should not happen?

Thanks for the help and for the great library!

Apollo’s InMemoryCache is normalized, which means that even if you request the same Person multiple times but with different fields across your application, in all of these cases the same Person object will be referenced in the cache. This means that if you fire off a mutation that changes a field on this particular Person (tags in your example), you will have to perform only a single cache update:

    update: (cache, { data }) => {
            id: 'the cache id of your Person object you wish to modify',
            fields: {
                tags: (existingTags, { toReference }) => (
                    [...existingTags, toReference(data.mutationApplyTagToListOfPersons)]