...

/

Local State Management with Apollo Client in React

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 ...