Updating Apollo Client Cache
Learn how to manually update Apollo Client's cache to improve our GraphQL application's performance.
Now that we’ve covered how Apollo Cache works, let’s see how we can use it more efficiently instead of re-fetching data every time we send a mutation. By the end of this lesson, we’ll see how we can trigger cache updates either by constructing correct queries or by implementing code that manually updates objects in Apollo Cache when we perform a mutation.
We’ll learn a few more techniques for updating Apollo Client cache in upcoming lessons when we learn how optimistic mutations and implement pagination in our application.
When the cache is updated
As we saw in the previous lesson, Apollo Client knows a lot about the structure of the responses and uses this information to normalize data in the client-side cache. It can also use this information to automatically update existing cache values.
Let’s look into when Apollo automatically updates a client’s cache without much effort on our side:
- When a mutation performs an update to a single object. If we update some fields of an object using a mutation, Apollo Client automatically updates changed fields if they’re returned in a mutation response.
- When we perform a query or a mutation that returns multiple objects. If we return objects from a query or a mutation, Apollo Client automatically stores them in the cache.
At this stage, you might wonder why we had to refetch data when we were implementing the upvoting functionality. We had to because it was updating a single object, and it returned the only field updated by the mutation, which was numberOfVotes
. To better understand this, let’s look at the mutation definition that we used previously.
Get hands-on with 1400+ tech skills courses.