Today I Learned

hashrocket A Hashrocket project

Manually update Apollo Graphql Cache

Usually you structure your graphql queries and mutations in a way that the cache just works out of the box. But there are times that you need to manually update the graphql cache then you can call updateQuery:

const client = useApolloClient();
const preferences = {abc: "xyz"};

function updateCache() {
  client.cache.updateQuery({ query: MY_QUERY }, (data) => {
    if (!data.preferences) {
      return { ...data, preferences };
    }
  });
}

Note that the return is optional, so if your update function returns undefined then it will keep the cache intact, without updating anything.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.