How to Deal With Cache Update Hell in Apollo Client

Using refetchQueries prop provides a shortcut for updating your User Interface after a mutatuion.

TL;DR: Instead of updating Apollo Client’s cached queries manually, using its refetchQueries prop provides a shortcut for updating your User Interface after a mutatuion.

Introduction

I am currently working on a little fun project to explore more in depth the use of Apollo Client in React. I stumbled upon this issue on Github, when I wanted to find a better way to update my cached queries after a GraphQL mutation.
Manually updating the cache.
Manually updating the cache.

The situation Let’s say we have React Component class that somewhere inside of render()returns some jsx with a Mutation component and a method onUpdate() . In my case, I am creating a new Board type in my database inside of a Modal on the index/ page of my web app, which also lists all of my current boards. After this is done, I need to update my UI accordingly.

According to the Docs, I’m supposed to update the cache for my query MYBOARDS_QUERY to pull this off:

The Problem

This does not look problematic yet, right? But here’s the thing — in one of my other mutations, the mutation should update a query that returns some complex data which is transformed on the server-side of things. I do not want to replicate all that code on the client side, so there must be a way to just refetch my query when I’m done.

The Solution

And thankfully, there is: Mutation components receive a prop called refetchQueries , which receives an array of strings with the query names.

The way this works is that it actually refreshes all cached queries of those specified names with their current variables. This might not be what you want in all cases, but could avoid some hidden dependencies inside your code where you do some manual updating and the queries change at some later point in time.

Why do I even write about this? I’ve spent quite some time trying to get my transformations to work on the client side. Then I’ve spent time trying to screen the docs for some sort ofrefetch() method on the query inside of my onUpdate() method. And then, finally, did I end up on Github where people where discussing this exact same issue and possible solutions.

I hope this saves you some time!

Never miss a post from Sumit Sharma, when you sign up for Ednsquare.