Local resolvers
Manage local data with GraphQL like resolvers
📄 NOTE: We recommend using field policies instead of local resolvers as described in Local-only fields.
Local resolver support will be moved out of the core of Apollo Client in a future major release. The same or similar functionality will be available via
ApolloLink
, as described in this issue.
We've learned how to manage remote data from our GraphQL server with Apollo Client, but what should we do with our local data? We want to be able to access boolean flags and device API results from multiple components in our app, but don't want to maintain a separate Redux or MobX store. Ideally, we would like the Apollo cache to be the single source of truth for all data in our client application.
Apollo Client (>= 2.5) has built-in local state handling capabilities that allow you to store your local data inside the Apollo cache alongside your remote data. To access your local data, just query it with GraphQL. You can even request local and server data within the same query!
In this section, you'll learn how Apollo Client can help simplify local state management in your app. We'll cover how client-side resolvers can help us execute local queries and mutations. You'll also learn how to query and update the cache with the @client
directive.
Please note that this documentation is intended to be used to familiarize yourself with Apollo Client's local state management capabilities, and serve as a reference guide. If you're looking for a step by step tutorial outlining how to handle local state with Apollo Client (and leverage other Apollo components to build a fullstack application), please refer to the full-stack quickstart course.
Updating local state
There are two main ways to perform local state mutations. The first way is to directly write to the cache by calling cache.writeQuery
. Direct writes are great for one-off mutations that don't depend on the data that's currently in the cache, such as writing a single value. The second way is by leveraging the useMutation
hook with a GraphQL mutation that calls a local client-side resolver. We recommend using resolvers if your mutation depends on existing values in the cache, such as adding an item to a list or toggling a boolean.
Direct writes
Direct writes to the cache do not require a GraphQL mutation or a resolver function. They leverage your Apollo Client instance directly by accessing the client
property returned from the useApolloClient
hook, made available in the useQuery
hook result, or within the render prop function of the ApolloConsumer
component. We recommend using this strategy for simple writes, such as writing a string, or one-off writes. It's important to note that direct writes are not implemented as GraphQL mutations under the hood, so you shouldn't include them in your schema. They also do not validate that the data you're writing to the cache is in the shape of valid GraphQL data. If either of these features are important to you, you should opt to use a local resolver instead.
1import React from "react";
2import { useApolloClient } from "@apollo/client";
3
4import Link from "./Link";
5
6function FilterLink({ filter, children }) {
7 const client = useApolloClient();
8 return (
9 <Link
10 onClick={() => client.writeQuery({
11 query: gql`query GetVisibilityFilter { visibilityFilter }`,
12 data: { visibilityFilter: filter },
13 })}
14 >
15 {children}
16 </Link>
17 );
18}
The ApolloConsumer
render prop function is called with a single value, the Apollo Client instance. You can think of the ApolloConsumer
component as being similar to the Consumer
component from the React context API. From the client instance, you can directly call client.writeQuery
and pass in the data you'd like to write to the cache.
What if we want to immediately subscribe to the data we just wrote to the cache? Let's create an active
property on the link that marks the link's filter as active if it's the same as the current visibilityFilter
in the cache. To immediately subscribe to a client-side mutation, we can use useQuery
. The useQuery
hook also makes the client instance available in its result object.
1import React from "react";
2import { gql, useQuery } from "@apollo/client";
3
4import Link from "./Link";
5
6const GET_VISIBILITY_FILTER = gql`
7 query GetVisibilityFilter {
8 visibilityFilter @client
9 }
10`;
11
12function FilterLink({ filter, children }) {
13 const { data, client } = useQuery(GET_VISIBILITY_FILTER);
14 return (
15 <Link
16 onClick={() => client.writeQuery({
17 query: GET_VISIBILITY_FILTER,
18 data: { visibilityFilter: filter },
19 })}
20 active={data.visibilityFilter === filter}
21 >
22 {children}
23 </Link>
24 )
25}
You'll notice in our query that we have a @client
directive next to our visibilityFilter
field. This tells Apollo Client to fetch the field data locally (either from the cache or using a local resolver), instead of sending it to our GraphQL server. Once you call client.writeQuery
, the query result on the render prop function will automatically update. All cache writes and reads are synchronous, so you don't have to worry about loading state.
Local resolvers
If you'd like to implement your local state update as a GraphQL mutation, then you'll need to specify a function in your local resolver map. The resolver map is an object with resolver functions for each GraphQL object type. To visualize how this all lines up, it's useful to think of a GraphQL query or mutation as a tree of function calls for each field. These function calls resolve to data or another function call. So when a GraphQL query is run through Apollo Client, it looks for a way to essentially run functions for each field in the query. When it finds an @client
directive on a field, it turns to its internal resolver map looking for a function it can run for that field.
To help make local resolvers more flexible, the signature of a resolver function is the exact same as resolver functions on the server built with Apollo Server. Let's recap the four parameters of a resolver function:
1fieldName: (obj, args, context, info) => result;
obj
: The object containing the result returned from the resolver on the parent field or theROOT_QUERY
object in the case of a top-level query or mutation.args
: An object containing all of the arguments passed into the field. For example, if you called a mutation withupdateNetworkStatus(isConnected: true)
, theargs
object would be{ isConnected: true }
.context
: An object of contextual information shared between your React components and your Apollo Client network stack. In addition to any custom context properties that may be present, local resolvers always receive the following:context.client
: The Apollo Client instance.context.cache
: The Apollo Cache instance, which can be used to manipulate the cache withcontext.cache.readQuery
,.writeQuery
,.readFragment
,.writeFragment
,.modify
, and.evict
. You can learn more about these methods in Managing the cache.context.getCacheKey
: Get a key from the cache using a__typename
andid
.
info
: Information about the execution state of the query. You will probably never have to use this one.
Let's take a look at an example of a resolver where we toggle a todo's completed status:
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 resolvers: {
6 Mutation: {
7 toggleTodo: (_root, variables, { cache }) => {
8 cache.modify({
9 id: cache.identify({
10 __typename: 'TodoItem',
11 id: variables.id,
12 }),
13 fields: {
14 completed: value => !value,
15 },
16 });
17 return null;
18 },
19 },
20 },
21});
In previous versions of Apollo Client, toggling the completed
status of the TodoItem
required reading a fragment from the cache, modifying the result by negating the completed
boolean, and then writing the fragment back into the cache. Apollo Client 3.0 introduced the cache.modify
method as an easier and faster way to update specific fields within a given entity object. To determine the ID of the entity, we pass the __typename
and primary key fields of the object to cache.identify
method.
Once we toggle the completed
field, since we don't plan on using the mutation's return result in our UI, we return null
since all GraphQL types are nullable by default.
Let's learn how to trigger our toggleTodo
mutation from our component:
1import React from "react"
2import { gql, useMutation } from "@apollo/client";
3
4const TOGGLE_TODO = gql`
5 mutation ToggleTodo($id: Int!) {
6 toggleTodo(id: $id) @client
7 }
8`;
9
10function Todo({ id, completed, text }) {
11 const [toggleTodo] = useMutation(TOGGLE_TODO, { variables: { id } });
12 return (
13 <li
14 onClick={toggleTodo}
15 style={{
16 textDecoration: completed ? "line-through" : "none",
17 }}
18 >
19 {text}
20 </li>
21 );
22}
First, we create a GraphQL mutation that takes the todo's id we want to toggle as its only argument. We indicate that this is a local mutation by marking the field with a @client
directive. This will tell Apollo Client to call our local toggleTodo
mutation resolver in order to resolve the field. Then, we create a component with useMutation
just as we would for a remote mutation. Finally, pass in your GraphQL mutation to your component and trigger it from within the UI in your render prop function.
Querying local state
Querying for local data is very similar to querying your GraphQL server. The only difference is that you add a @client
directive on your local fields to indicate they should be resolved from the Apollo Client cache or a local resolver function. Let's look at an example:
1import React from "react";
2import { gql, useQuery } from "@apollo/client";
3
4import Todo from "./Todo";
5
6const GET_TODOS = gql`
7 query GetTodos {
8 todos @client {
9 id
10 completed
11 text
12 }
13 visibilityFilter @client
14 }
15`;
16
17function TodoList() {
18 const { data: { todos, visibilityFilter } } = useQuery(GET_TODOS);
19 return (
20 <ul>
21 {getVisibleTodos(todos, visibilityFilter).map(todo => (
22 <Todo key={todo.id} {...todo} />
23 ))}
24 </ul>
25 );
26}
Here we create our GraphQL query and add @client
directives to todos
and visibilityFilter
. We then pass the query to the useQuery
hook. The @client
directives here let useQuery
component know that todos
and visibilityFilter
should be pulled from the Apollo Client cache or resolved using pre-defined local resolvers. The following sections help explain how both options work in more detail.
⚠️ Since the above query runs as soon as the component is mounted, what do we do if there are no todos in the cache or there aren't any local resolvers defined to help calculate
todos
? We need to write an initial state to the cache before the query is run to prevent it from erroring out. Refer to the Initializing the cache section below for more information.
Initializing the cache
Often, you'll need to write an initial state to the cache so any components querying data before a mutation is triggered don't error out. To accomplish this, you can use cache.writeQuery
to prep the cache with initial values.
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const cache = new InMemoryCache();
4const client = new ApolloClient({
5 cache,
6 resolvers: { /* ... */ },
7});
8
9cache.writeQuery({
10 query: gql`
11 query GetTodosNetworkStatusAndFilter {
12 todos
13 visibilityFilter
14 networkStatus {
15 isConnected
16 }
17 }
18 `,
19 data: {
20 todos: [],
21 visibilityFilter: 'SHOW_ALL',
22 networkStatus: {
23 __typename: 'NetworkStatus',
24 isConnected: false,
25 },
26 },
27});
Sometimes you may need to reset the store in your application, when a user logs out for example. If you call client.resetStore
anywhere in your application, you will likely want to initialize your cache again. You can do this using the client.onResetStore
method to register a callback that will call cache.writeQuery
again.
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const cache = new InMemoryCache();
4const client = new ApolloClient({
5 cache,
6 resolvers: { /* ... */ },
7});
8
9function writeInitialData() {
10 cache.writeQuery({
11 query: gql`
12 query GetTodosNetworkStatusAndFilter {
13 todos
14 visibilityFilter
15 networkStatus {
16 isConnected
17 }
18 }
19 `,
20 data: {
21 todos: [],
22 visibilityFilter: 'SHOW_ALL',
23 networkStatus: {
24 __typename: 'NetworkStatus',
25 isConnected: false,
26 },
27 },
28 });
29}
30
31writeInitialData();
32
33client.onResetStore(writeInitialData);
Local data query flow
When a query containing @client
directives is executed, Apollo Client runs through a few sequential steps to try to find a result for the @client
field. Let's use the following query to walk through the local data look up flow:
1const GET_LAUNCH_DETAILS = gql`
2 query LaunchDetails($launchId: ID!) {
3 launch(id: $launchId) {
4 isInCart @client
5 site
6 rocket {
7 type
8 }
9 }
10 }
11`;
This query includes a mixture of both remote and local fields. isInCart
is the only field marked with an @client
directive, so it's the field we'll focus on. When Apollo Client executes this query and tries to find a result for the isInCart
field, it runs through the following steps:
Has a resolver function been set (either through the
ApolloClient
constructorresolvers
parameter or Apollo Client'ssetResolvers
/addResolvers
methods) that is associated with the field nameisInCart
? If yes, run and return the result from the resolver function.If a matching resolver function can't be found, check the Apollo Client cache to see if a
isInCart
value can be found directly. If so, return that value.
Let's look at both of these steps more closely.
Resolving
@client
data with the help of local resolvers (step 1 above) is explained in Handling@client
fields with resolvers.Loading
@client
data from the cache (step 2 above) is explained in Handling@client
fields with the cache.
Handling @client
fields with resolvers
Local resolvers are very similar to remote resolvers. Instead of sending your GraphQL query to a remote GraphQL endpoint, which then runs resolver functions against your query to populate and return a result set, Apollo Client runs locally defined resolver functions against any fields marked with the @client
directive. Let's look at an example:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const GET_CART_ITEMS = gql`
4 query GetCartItems {
5 cartItems @client
6 }
7`;
8
9const cache = new InMemoryCache();
10cache.writeQuery({
11 query: GET_CART_ITEMS,
12 data: {
13 cartItems: [],
14 },
15});
16
17const client = new ApolloClient({
18 cache,
19 link: new HttpLink({
20 uri: 'http://localhost:4000/graphql',
21 }),
22 resolvers: {
23 Launch: {
24 isInCart: (launch, _args, { cache }) => {
25 const { cartItems } = cache.readQuery({ query: GET_CART_ITEMS });
26 return cartItems.includes(launch.id);
27 },
28 },
29 },
30});
31
32const GET_LAUNCH_DETAILS = gql`
33 query LaunchDetails($launchId: ID!) {
34 launch(id: $launchId) {
35 isInCart @client
36 site
37 rocket {
38 type
39 }
40 }
41 }
42`;
43
44// ... run the query using client.query, a <Query /> component, etc.
Here when the GET_LAUNCH_DETAILS
query is executed, Apollo Client looks for a local resolver associated with the isInCart
field. Since we've defined a local resolver for the isInCart
field in the ApolloClient
constructor, it finds a resolver it can use. This resolver function is run, then the result is calculated and merged in with the rest of the query result (if a local resolver can't be found, Apollo Client will check the cache for a matching field - see Local data query flow for more details).
Setting resolvers through ApolloClient
's constructor resolvers
parameter, or through its setResolvers
/ addResolvers
methods, adds resolvers to Apollo Client's internal resolver map (refer to the Local resolvers section for more details concerning the resolver map). In the above example we added a isInCart
resolver, for the Launch
GraphQL object type, to the resolver map. Let's look at the isInCart
resolver function more closely:
1 resolvers: {
2 Launch: {
3 isInCart: (launch, _args, { cache }) => {
4 const { cartItems } = cache.readQuery({ query: GET_CART_ITEMS });
5 return cartItems.includes(launch.id);
6 },
7 },
8 },
launch
holds the data returned from the server for the rest of the query, which means in this case we can use launch
to get the current launch id
. We aren't using any arguments in this resolver, so we can skip the second resolver parameter. From the context
however (the third parameter), we're using the cache
reference, to work directly with the cache ourselves. So in this resolver, we're making a call directly to the cache to get all cart items, checking to see if any of those loaded cart items matches the parent launch.id
, and returning true
/ false
accordingly. The returned boolean is then incorporated back into the result of running the original query.
Just like resolvers on the server, local resolvers are extremely flexible. They can be used to perform any kind of local computation you want, before returning a result for the specified field. You can manually query (or write to) the cache in different ways, call other helper utilities or libraries to prep/validate/clean data, track statistics, call into other data stores to prep a result, etc.
Integrating @client
into remote queries
While Apollo Client’s local state handling features can be used to work with local state exclusively, most Apollo based applications are built to work with remote data sources. To address this, Apollo Client supports mixing @client
based local resolvers with remote queries, as well as using @client
based fields as arguments to remote queries, in the same request.
The @client
directive can be used on any GraphQL selection set or field, to identify that the result of that field should be loaded locally with the help of a local resolver:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const MEMBER_DETAILS = gql`
4 query Member {
5 member {
6 name
7 role
8 isLoggedIn @client
9 }
10 }
11`;
12
13const client = new ApolloClient({
14 link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
15 cache: new InMemoryCache(),
16 resolvers: {
17 Member: {
18 isLoggedIn() {
19 return someInternalLoginVerificationFunction();
20 }
21 }
22 },
23});
24
25// ... run the query using client.query, the <Query /> component, etc.
When the above MEMBER_DETAILS
query is fired by Apollo Client (assuming we're talking to a network based GraphQL API), the @client
isLoggedIn
field is first stripped from the document, and the remaining query is sent over the network to the GraphQL API. After the query has been handled by the remote resolvers and the result is passed back to Apollo Client from the API, the @client
parts of the original query are then run against any defined local resolvers, their results are merged with the network results, and the final resulting data is returned as the response to the original operation. So in the above example, isLoggedIn
is stripped before the rest of the query is sent and handled by the network API, then when the results come back isLoggedIn
is calculated by running the isLoggedIn()
function from the resolver map. Local and network results are merged together, and the final response is made available to the application.
The @client
directive can be used with entire selection sets as well:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const MEMBER_DETAILS = gql`
4 query Member {
5 member {
6 name
7 role
8 session @client {
9 isLoggedIn
10 connectionCount
11 errors
12 }
13 }
14 }
15`;
16
17const client = new ApolloClient({
18 link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
19 cache: new InMemoryCache(),
20 resolvers: {
21 Member: {
22 session() {
23 return {
24 __typename: 'Session',
25 isLoggedIn: someInternalLoginVerificationFunction(),
26 connectionCount: calculateOpenConnections(),
27 errors: sessionError(),
28 };
29 }
30 }
31 },
32});
Apollo Client supports the merging of local @client
results and remote results for Queries, Mutations and Subscriptions.
Async local resolvers
Apollo Client supports asynchronous local resolver functions. These functions can either be async
functions or ordinary functions that return a Promise
. Asynchronous resolvers are useful when they need to return data from an asynchronous API.
⚠️ If you would like to hit a REST endpoint from your resolver, we recommend checking out
apollo-link-rest
instead, which is a more complete solution for using REST endpoints with Apollo Client.
For React Native and most browser APIs, you should set up a listener in a component lifecycle method and pass in your mutation trigger function as the callback instead of using an async resolver. However, an async
resolver function is often the most convenient way to consume asynchronous device APIs:
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2import { CameraRoll } from 'react-native';
3
4const client = new ApolloClient({
5 cache: new InMemoryCache(),
6 resolvers: {
7 Query: {
8 async cameraRoll(_, { assetType }) {
9 try {
10 const media = await CameraRoll.getPhotos({
11 first: 20,
12 assetType,
13 });
14
15 return {
16 ...media,
17 id: assetType,
18 __typename: 'CameraRoll',
19 };
20 } catch (e) {
21 console.error(e);
22 return null;
23 }
24 },
25 },
26 },
27});
CameraRoll.getPhotos()
returns a Promise
resolving to an object with an edges
property, which is an array of camera node objects, and a page_info
property, which is an object with pagination information. This is a great use case for GraphQL, since we can filter down the return value to only the data that our components consume.
1import { gql } from "@apollo/client";
2
3const GET_PHOTOS = gql`
4 query GetPhotos($assetType: String!) {
5 cameraRoll(assetType: $assetType) @client {
6 id
7 edges {
8 node {
9 image {
10 uri
11 }
12 location {
13 latitude
14 longitude
15 }
16 }
17 }
18 }
19 }
20`;
Handling @client
fields with the cache
As outlined in Handling @client
fields with resolvers, @client
fields can be resolved with the help of local resolver functions. However, it's important to note that local resolvers are not always required when using an @client
directive. Fields marked with @client
can still be resolved locally, by pulling matching values out of the cache directly. For example:
1import React from "react";
2import ReactDOM from "react-dom";
3import {
4 ApolloClient,
5 InMemoryCache,
6 HttpLink,
7 ApolloProvider,
8 useQuery,
9 gql
10} from "@apollo/client";
11
12import Pages from "./pages";
13import Login from "./pages/login";
14
15const cache = new InMemoryCache();
16const client = new ApolloClient({
17 cache,
18 link: new HttpLink({ uri: "http://localhost:4000/graphql" }),
19 resolvers: {},
20});
21
22const IS_LOGGED_IN = gql`
23 query IsUserLoggedIn {
24 isLoggedIn @client
25 }
26`;
27
28cache.writeQuery({
29 query: IS_LOGGED_IN,
30 data: {
31 isLoggedIn: !!localStorage.getItem("token"),
32 },
33});
34
35function App() {
36 const { data } = useQuery(IS_LOGGED_IN);
37 return data.isLoggedIn ? <Pages /> : <Login />;
38}
39
40ReactDOM.render(
41 <ApolloProvider client={client}>
42 <App />
43 </ApolloProvider>,
44 document.getElementById("root"),
45);
In the above example, we first prep the cache using cache.writeQuery
to store a value for the isLoggedIn
field. We then run the IS_LOGGED_IN
query via an Apollo Client useQuery
hook, which includes an @client
directive. When Apollo Client executes the IS_LOGGED_IN
query, it first looks for a local resolver that can be used to handle the @client
field. When it can't find one, it falls back on trying to pull the specified field out of the cache. So in this case, the data
value returned by the useQuery
hook has a isLoggedIn
property available, which includes the isLoggedIn
result (!!localStorage.getItem('token')
) pulled directly from the cache.
⚠️ If you want to use Apollo Client's
@client
support to query the cache without using local resolvers, you must pass an empty object into theApolloClient
constructorresolvers
option. Without this Apollo Client will not enable its integrated@client
support, which means your@client
based queries will be passed to the Apollo Client link chain. You can find more details about why this is necessary here.
Pulling @client
field values directly out of the cache isn't quite as flexible as local resolver functions, since local resolvers can perform extra computations before returning a result. Depending on your application's needs however, loading @client
fields directly from the cache might be a simpler option. Apollo Client doesn't restrict combining both approaches, so feel free to mix and match. If the need arises, you can pull some @client
values from the cache, and resolve others with local resolvers, all in the same query.
Working with fetch policies
Before Apollo Client executes a query, one of the first things it does is check to see which fetchPolicy
it has been configured to use. It does this so it knows where it should attempt to resolve the query from first, either the cache or the network. When running a query, Apollo Client treats @client
based local resolvers just like it does remote resolvers, in that it will adhere to its defined fetchPolicy
to know where to attempt to pull data from first. When working with local resolvers, it's important to understand how fetch policies impact the running of resolver functions, since by default local resolver functions are not run on every request. This is because the result of running a local resolver is cached with the rest of the query result, and pulled from the cache on the next request. Let's look at an example:
1import React, { Fragment } from "react";
2import { useQuery, gql } from "@apollo/client";
3
4import { Loading, Header, LaunchDetail } from "../components";
5import { ActionButton } from "../containers";
6
7export const GET_LAUNCH_DETAILS = gql`
8 query LaunchDetails($launchId: ID!) {
9 launch(id: $launchId) {
10 isInCart @client
11 site
12 rocket {
13 type
14 }
15 }
16 }
17`;
18
19export default function Launch({ launchId }) {
20 const { loading, error, data } = useQuery(
21 GET_LAUNCH_DETAILS,
22 { variables: { launchId } }
23 );
24
25 if (loading) return <Loading />;
26 if (error) return <p>ERROR: {error.message}</p>;
27
28 return (
29 <Fragment>
30 <Header image={data.launch.mission.missionPatch}>
31 {data.launch.mission.name}
32 </Header>
33 <LaunchDetail {...data.launch} />
34 <ActionButton {...data.launch} />
35 </Fragment>
36 );
37}
In the above example we're using an Apollo Client useQuery
hook to run the GET_LAUNCH_DETAILS
query. The @client
based isInCart
field is configured to pull its data from the following resolver:
1import { GET_CART_ITEMS } from './pages/cart';
2
3export const resolvers = {
4 Launch: {
5 isInCart: (launch, _, { cache }) => {
6 const { cartItems } = cache.readQuery({ query: GET_CART_ITEMS });
7 return cartItems.includes(launch.id);
8 },
9 },
10};
Let's assume we're starting with an empty cache. Since we haven't specified a fetchPolicy
prop in our useQuery
call, we're using Apollo Client's default cache-first
fetchPolicy
. This means when the GET_LAUNCH_DETAILS
query is run, it checks the cache first to see if it can find a result. It's important to note that when the cache is checked the entire query is run against the cache, but any @client
associated local resolvers are skipped (not run). So the cache is queried with the following (it's as if the @client
directive was never specified):
1launch(id: $launchId) {
2 isInCart
3 site
4 rocket {
5 type
6 }
7}
In this case a result can't be extracted from the cache (since our cache is empty), so behind the scenes Apollo Client moves further down the query execution path. At its next step, it essentially splits the original query into two parts - the part that has @client
fields and the part that will be fired over the network. Both parts are then executed - results are fetched from the network, and results are calculated by running local resolvers. The results from the local resolvers and from the network are then merged together, and the final result is written to the cache and returned. So after our first run, we now have a result in the cache for the original query, that includes data for both the @client
parts and network parts of the query.
When the GET_LAUNCH_DETAILS
query is run a second time, again since we're using Apollo Client's default fetchPolicy
of cache-first
, the cache is checked first for a result. This time a full result can be found for the query, so that result is returned through our useQuery
call. Our @client
field local resolvers aren't fired since the result we're looking for can already be extracted from the cache.
In a lot of situations treating local resolvers just like remote resolvers, by having them adhere to the same fetchPolicy
, makes a lot of sense. Once you have the data you're looking for, which might have been fetched remotely or calculated using a local resolver, you can cache it and avoid recalculating/re-fetching it again on a subsequent request. But what if you're using local resolvers to run calculations that you need fired on every request? There are a few different ways this can be handled. You can switch your query to use a fetchPolicy
that forces your entire query to run on each request, like no-cache
or network-only
. This will make sure your local resolvers fire on every request, but it will also make sure your network based query components fire on every request. Depending on your use case this might be okay, but what if you want the network parts of your query to leverage the cache, and just want your @client
parts to run on every request? We'll cover a more flexible option for this in the Forcing resolvers with @client(always: true)
section.
Forcing resolvers with @client(always: true)
Apollo Client leverages its cache to help reduce the network overhead required when constantly making requests for the same data. By default, @client
based fields leverage the cache in the exact same manner as remote fields. After a local resolver is run, its result is cached alongside any remote results. This way the next time a query is fired that can find its results in the cache, those results are used, and any associated local resolvers are not fired again (until the data is either removed from the cache or the query is updated to use a no-cache
or network-only
fetchPolicy
).
While leveraging the cache for both local and remote results can be super helpful in a lot of cases, it's not always the best fit. We might want to use a local resolver to calculate a dynamic value that needs to be refreshed on every request, while at the same time continue to use the cache for the network based parts of our query. To support this use case, Apollo Client's @client
directive accepts an always
argument, that when set to true
will ensure that the associated local resolver is run on every request. Looking at an example:
1import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 resolvers: {
6 Query: {
7 isLoggedIn() {
8 return !!localStorage.getItem('token');
9 },
10 },
11 },
12});
13
14const IS_LOGGED_IN = gql`
15 query IsUserLoggedIn {
16 isLoggedIn @client(always: true)
17 }
18`;
19
20// ... run the query using client.query, a <Query /> component, etc.
The isLoggedIn
resolver above is checking to see if an authentication token exists in localStorage
. In this example, we want to make sure that every time the IS_LOGGED_IN
query is executed, the isLoggedIn
local resolver is also fired, so that we have the most up to date login information. To do this, we're using a @client(always: true)
directive in the query, for the isLoggedIn
field. If we didn't include always: true
, then the local resolver would fire based on the queries fetchPolicy
, which means we could be getting back a cached value for isLoggedIn
. Using @client(always: true)
ensures that we're always getting the direct result of running the associated local resolver.
⚠️ Please consider the impact of using
@client(always: true)
carefully. While forcing a local resolver to run on every request can be useful, if that resolver is computationally expensive or has side effects, you could be negatively impacting your application. We recommend leveraging the cache as much as possible when using local resolvers, to help with application performance.@client(always: true)
is helpful to have in your tool-belt, but letting local resolvers adhere to a queryfetchPolicy
should be the preferred choice.
While @client(always: true)
ensures that a local resolver is always fired, it's important to note that if a query is using a fetchPolicy
that leverages the cache first (cache-first
, cache-and-network
, cache-only
), the query is still attempted to be resolved from the cache first, before the local resolver is fired. This happens because @client(always: true)
use could be mixed with normal @client
use in the same query, which means we want part of the query to adhere to the defined fetchPolicy
. The benefit of this is that anything that can be loaded from the cache first is made available to your @client(always: true)
resolver function, as its first parameter. So even though you've used @client(always: true)
to identify that you want to always run a specific resolver, within that resolver you can look at the loaded cache values for the query, and decide if you want to proceed with running the resolver.
Using @client
fields as variables
Apollo Client provides a way to use an @client
field result as a variable for a selection set or field, in the same operation. So instead of running an @client
based query first, getting the local result, then running a second query using the loaded local result as a variable, everything can be handled in one request. This is achieved by combining the @client
directive with the @export(as: "variableName")
directive:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const query = gql`
4 query CurrentAuthorPostCount($authorId: Int!) {
5 currentAuthorId @client @export(as: "authorId")
6 postCount(authorId: $authorId)
7 }
8`;
9
10const cache = new InMemoryCache();
11const client = new ApolloClient({
12 link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
13 cache,
14 resolvers: {},
15});
16
17cache.writeQuery({
18 query: gql`query GetCurrentAuthorId { currentAuthorId }`,
19 data: {
20 currentAuthorId: 12345,
21 },
22});
23
24// ... run the query using client.query, the <Query /> component, etc.
In the example above, currentAuthorId
is first loaded from the cache, then passed into the subsequent postCount
field as the authorId
variable (specified by the @export(as: "authorId")
directive). The @export
directive can also be used on specific fields within a selection set, like:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const query = gql`
4 query CurrentAuthorPostCount($authorId: Int!) {
5 currentAuthor @client {
6 name
7 authorId @export(as: "authorId")
8 }
9 postCount(authorId: $authorId)
10 }
11`;
12
13const cache = new InMemoryCache();
14const client = new ApolloClient({
15 link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
16 cache,
17 resolvers: {},
18});
19
20cache.writeQuery({
21 query: gql`
22 query GetCurrentAuthor {
23 currentAuthor {
24 name
25 authorId
26 }
27 }
28 `,
29 data: {
30 currentAuthor: {
31 __typename: 'Author',
32 name: 'John Smith',
33 authorId: 12345,
34 },
35 },
36});
37
38// ... run the query using client.query, the <Query /> component, etc.
Here the authorId
variable is set from the authorId
field loaded from the cache stored currentAuthor
. @export
variable use isn't limited to remote queries; it can also be used to define variables for other @client
fields or selection sets:
1import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
2
3const query = gql`
4 query CurrentAuthorPostCount($authorId: Int!) {
5 currentAuthorId @client @export(as: "authorId")
6 postCount(authorId: $authorId) @client
7 }
8`;
9
10const cache = new InMemoryCache();
11const client = new ApolloClient({
12 cache,
13 resolvers: {
14 Query: {
15 postCount(_, { authorId }) {
16 return authorId === 12345 ? 100 : 0;
17 },
18 },
19 },
20});
21
22cache.writeQuery({
23 query: gql`{ currentAuthorId }`,
24 data: {
25 currentAuthorId: 12345,
26 },
27});
28
29// ... run the query using client.query, the <Query /> component, etc.
So here the currentAuthorId
is loaded from the cache, then passed into the postCount
local resolver as authorId
.
A few important notes about @export
use:
Apollo Client currently only supports using the
@export
directive to store variables for local data.@export
must be used with@client
.@client @export
use might appear to go against the GraphQL specification, given that the execution order of an operation looks like it could affect the result. From the Normal and Serial Execution section of the GraphQL spec:
... the resolution of fields other than top‐level mutation fields must always be side effect‐free and idempotent, the execution order must not affect the result, and hence the server has the freedom to execute the field entries in whatever order it deems optimal.
Apollo Client currently only supports the use of the @export
directive when mixed with the @client
directive. It prepares @export
variables by first running through an operation that has @client @export
directives, extracting the specified @export
variables, then attempting to resolve the value of those variables from the local cache or local resolvers. Once a map of variable names to local values is built up, that map is then used to populate the variables passed in when running the server based GraphQL query. The execution order of the server based GraphQL query is not impacted by @export
use; the variables are prepped and organized before the server query runs, so the specification is being followed.
If you define multiple
@export
variables that use the same name, in a single operation, the value of the last@export
variable will be used as the variable value moving forward. When this happens Apollo Client will log a warning message (dev only).
Managing the cache
When you're using Apollo Client to work with local state, your Apollo cache becomes the single source of truth for all of your local and remote data. The Apollo cache API has several methods that can assist you with updating and retrieving data. Let's walk through the most relevant methods, and explore some common use cases for each one.
cache.writeQuery
The easiest way to update the cache is with cache.writeQuery
. Here's how you use it in your resolver map for a simple update:
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 resolvers: {
6 Mutation: {
7 updateVisibilityFilter: (_, { visibilityFilter }, { cache }) => {
8 cache.writeQuery({
9 query: gql`query GetVisibilityFilter { visibilityFilter }`,
10 data: {
11 __typename: 'Filter',
12 visibilityFilter,
13 },
14 });
15 },
16 },
17 },
18};
The cache.writeFragment
method allows you to pass in an optional id
property to write a fragment to an existing object in the cache. This is useful if you want to add some client-side fields to an existing object in the cache.
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 resolvers: {
6 Mutation: {
7 updateUserEmail: (_, { id, email }, { cache }) => {
8 cache.writeFragment({
9 id: cache.identify({ __typename: "User", id }),
10 fragment: gql`fragment UserEmail on User { email }`,
11 data: { email },
12 });
13 },
14 },
15 },
16};
The cache.writeQuery
and cache.writeFragment
methods should cover most of your needs; however, there are some cases where the data you're writing to the cache depends on the data that's already there. In that scenario, you can either use a combination of cache.read{Query,Fragment}
followed by cache.write{Query,Fragment}
, or use cache.modify({ id, fields })
to update specific fields within the entity object identified by id
.
writeQuery and readQuery
Sometimes, the data you're writing to the cache depends on data that's already in the cache; for example, you're adding an item to a list or setting a property based on an existing property value. In that case, you should use cache.modify
to update specific existing fields. Let's look at an example where we add a todo to a list:
1import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
2
3let nextTodoId = 0;
4
5const cache = new InMemoryCache();
6
7cache.writeQuery({
8 query: gql`query GetTodos { todos { ... } }`,
9 data: { todos: [] },
10});
11
12const client = new ApolloClient({
13 resolvers: {
14 Mutation: {
15 addTodo: (_, { text }, { cache }) => {
16 const query = gql`
17 query GetTodos {
18 todos @client {
19 id
20 text
21 completed
22 }
23 }
24 `;
25
26 const previous = cache.readQuery({ query });
27 const newTodo = { id: nextTodoId++, text, completed: false, __typename: 'TodoItem' };
28 const data = {
29 todos: [...previous.todos, newTodo],
30 };
31
32 cache.writeQuery({ query, data });
33 return newTodo;
34 },
35 },
36 },
37});
In order to add our todo to the list, we need the todos that are currently in the cache, which is why we call cache.readQuery
to retrieve them. cache.readQuery
will throw an error if the data isn't in the cache, so we need to provide an initial state. This is why we're calling cache.writeQuery
with the empty array of todos after creating the InMemoryCache
.
writeFragment and readFragment
cache.readFragment
is similar to cache.readQuery
except you pass in a fragment. This allows for greater flexibility because you can read from any entry in the cache as long as you have its cache key. In contrast, cache.readQuery
only lets you read from the root of your cache.
Let's go back to our previous todo list example and see how cache.readFragment
can help us toggle one of our todos as completed.
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const client = new ApolloClient({
4 resolvers: {
5 Mutation: {
6 toggleTodo: (_, variables, { cache }) => {
7 const id = `TodoItem:${variables.id}`;
8 const fragment = gql`
9 fragment CompleteTodo on TodoItem {
10 completed
11 }
12 `;
13 const todo = cache.readFragment({ fragment, id });
14 const data = { ...todo, completed: !todo.completed };
15
16 cache.writeFragment({ fragment, id, data });
17 return null;
18 },
19 },
20 },
21});
In order to toggle our todo, we need the todo and its status from the cache, which is why we call cache.readFragment
and pass in a fragment to retrieve it. The id
we're passing into cache.readFragment
refers to its cache key. If you're using the InMemoryCache
and not overriding the dataIdFromObject
config property, your cache key should be __typename:id
.
Advanced
Code splitting
Depending on the complexity and size of your local resolvers, you might not always want to define them up front, when you create your initial ApolloClient
instance. If you have local resolvers that are only needed in a specific part of your application, you can leverage Apollo Client's addResolvers
and setResolvers
functions to adjust your resolver map at any point. This can be really useful when leveraging techniques like route based code-splitting, using something like react-loadable
.
Let's say we're building a messaging app and have a /stats
route that is used to return the total number of messages stored locally. If we use react-loadable
to load our Stats
component like:
1import Loadable from 'react-loadable';
2
3import Loading from './components/Loading';
4
5export const Stats = Loadable({
6 loader: () => import('./components/stats/Stats'),
7 loading: Loading,
8});
and wait until our Stats
component is called to define our local resolvers (using addResolvers
):
1import React from "react";
2import { ApolloConsumer, useApolloClient, useQuery, gql } from "@apollo/client";
3
4const GET_MESSAGE_COUNT = gql`
5 query GetMessageCount {
6 messageCount @client {
7 total
8 }
9 }
10`;
11
12const resolvers = {
13 Query: {
14 messageCount: (_, args, { cache }) => {
15 // ... calculate and return the number of messages in
16 // the cache ...
17 return {
18 total: 123,
19 __typename: "MessageCount",
20 };
21 },
22 },
23};
24
25export function MessageCount() {
26 const client = useApolloClient();
27 client.addResolvers(resolvers);
28
29 const { loading, data: { messageCount } } = useQuery(GET_MESSAGE_COUNT);
30
31 if (loading) return "Loading ...";
32
33 return (
34 <p>
35 Total number of messages: {messageCount.total}
36 </p>
37 );
38};
our local resolver code will only be included in the bundle a user downloads when (if) they access /stats
. It won't be included in the initial application bundle, which helps keep the size of our initial bundle down, and ultimately helps with download and application startup times.
API
Apollo Client local state handling is baked in, so you don't have to install anything extra. Local state management can be configured during ApolloClient
instantiation (via the ApolloClient
constructor) or by using the ApolloClient
local state API. Data in the cache can be managed through the ApolloCache
API.
ApolloClient
Constructor
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 resolvers: { ... },
6 typeDefs: { ... },
7});
Option | Type | Description |
---|---|---|
resolvers? | Resolvers | Resolvers[] | A map of resolver functions that your GraphQL queries and mutations call in order to read and write to the cache. |
typeDefs? | string | string[] | DocumentNode | DocumentNode[];<string> | A string representing your client-side schema written in the Schema Definition Language. This schema is not used for validation, but is used for introspection by the Apollo Client Devtools. |
None of these options are required. If you don't specify anything, you will still be able to use the @client
directive to query the Apollo Client cache.
Methods
1import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
2
3const client = new ApolloClient({
4 cache: new InMemoryCache(),
5 link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
6});
7
8client.setResolvers({ ... });
Method | Description |
---|---|
addResolvers(resolvers: Resolvers | Resolvers[]) | A map of resolver functions that your GraphQL queries and mutations call in order to read and write to the cache. Resolver functions added through addResolvers are added to the internal resolver function map, meaning any existing resolvers (that aren't overwritten) are preserved. |
setResolvers(resolvers: Resolvers | Resolvers[]) | A map of resolver functions that your GraphQL queries and mutations call in order to read and write to the cache. Resolver functions added through setResolvers overwrite all existing resolvers (a pre-existing resolver map is wiped out, before the new resolvers are added). |
getResolvers | Get the currently defined resolver map. |
setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher) | Set a custom FragmentMatcher to be used when resolving local state queries. |
Typescript interfaces/types:
1interface Resolvers {
2 [key: string]: {
3 [field: string]: (
4 rootValue?: any,
5 args?: any,
6 context?: any,
7 info?: any,
8 ) => any;
9 };
10}
11
12type FragmentMatcher = (
13 rootValue: any,
14 typeCondition: string,
15 context: any,
16) => boolean;
ApolloCache
Methods
1import { InMemoryCache } from '@apollo/client';
2
3const cache = new InMemoryCache();
4cache.writeQuery({
5 query: gql`query MyQuery {
6 isLoggedIn,
7 cartItems
8 }`,
9 data: {
10 isLoggedIn: !!localStorage.getItem('token'),
11 cartItems: [],
12 },
13});
Method | Description |
---|---|
writeQuery({ query, variables, data }) | Writes data to the root of the cache using the specified query to validate that the shape of the data you’re writing to the cache is the same as the shape of the data required by the query. Great for prepping the cache with initial data. |
readQuery({ query, variables }) | Read data from the cache for the specified query. |
writeFragment({ id, fragment, fragmentName, variables, data }) | Similar to writeQuery (writes data to the cache) but uses the specified fragment to validate that the shape of the data you’re writing to the cache is the same as the shape of the data required by the fragment. |
readFragment({ id, fragment, fragmentName, variables }) | Read data from the cache for the specified fragment. |
Deprecation notice
The idea of using client side resolvers to manage local state was first introduced into the Apollo Client ecosystem through the apollo-link-state
project. The Apollo Client team is always looking for ways to improve local state handling, so we decided to bring local resolver and @client
support into the Apollo Client core directly, in version 2.5. While managing state with local resolvers works well, the functionality offered by apollo-link-state
, and then from Apollo Client directly, was originally designed with certain imposed limitations due to its distance from the Apollo Client cache. Apollo Link's don't have direct access to the cache, which means apollo-link-state
had to implement an approach that couldn't feed or hook into the cache as seamlessly as we would have liked. The local resolver support merged into the Apollo Client core in version 2.5 was essentially a mirror of the Link approach, with a few adjustments to tie into the cache a little more closely. This means Apollo Client's local resolver approach is still a bit limited when it comes to being able to work with the cache more closely, and ultimately providing a better developer experience.
To help address limitations in the local resolver API, we have designed and implemented a new approach for managing local state in Apollo Client 3.0, that works as a direct extension of the cache. Field policies and reactive variables not only help provide a better developer experience from an API use and functionality point of view, but they also improve performance and provide a more reliable foundation for local state management. Re-thinking local state handling with the Apollo Client cache in mind has helped reduce a large number of local state bugs caused by local resolvers being a few too many layers removed from the cache internals.
The managing state with field policies section goes into more detail around what Apollo Client 3's new local state management capabilities look like. We highly recommend reviewing and considering the use of these new API's as a replacement for local resolvers. Local resolvers are still supported in Apollo Client 3 but will be moved out of the core module in a future major release.