Local State Management with Apollo Client in React

In this lesson, you will learn how to maintain and manage to update your local state using GraphQL Fragments and Apollo Client in React!

Behind the scenes of “starring” a repository

Let’s get back to the Repository component. You have experienced that the viewerHasStarred boolean updates in the Apollo Client’s cache after a mutation was successful. That’s great, because Apollo Client handles this for you, based on the mutation result.

If you have followed the code from the mutation lesson, you should probably see something like a toggling “Star” and “Unstar” label for the button. All of this happens because you returned the viewerHasStarred boolean in your mutation result. Apollo Client is clever enough to update the repository entity, which is normalized accessible in the cache. That’s the powerful default behavior, isn’t it? You don’t need to handle the local state management yourself since Apollo Client figures it out for you as long as you provide useful information in the mutation’s result.

Updating the Count of Stars

However, Apollo Client doesn’t update the count of stars after the mutation. Normally, it is assumed that the count of stars increments by one when it is starred, with the opposite for unstarring. Since we don’t return a count of stargazers in the mutation result, you have to handle the update in Apollo Client’s cache yourself.

Using Apollo Client’s refetchQueries option is the naive approach for a mutation call, or we can make use of a Mutation component to trigger a refetch for all queries where the query result might be affected by the mutation. But that’s not the best way to deal with this problem. This is because it costs another query request to keep the data consistent after a mutation. In a growing application, this approach will eventually become problematic.

Fortunately, the Apollo Client offers other functionalities to read/write manually from/to the cache locally without more network requests. The Mutation component offers a prop where you can insert update functionality that has access to the Apollo Client instance for the update mechanism.

Using GraphQL Fragments

Before implementing the update functionality for the local state management, let’s refactor another piece of code that will be useful for a local state update mechanism. The query definition next to your Profile component has grown to several fields with multiple object nestings. Previously, you learned about GraphQL fragments, and how they can be used to split parts of a query to reuse later.

Now, we will split all the field information you used for the repository’s node. You can define this fragment in the src/Repository/fragments.js file to keep it reusable for other components.

Get hands-on with 1200+ tech skills courses.