Interacting with cached data
The ApolloClient
object provides the following methods for interacting
with cached data:
readQuery
readFragment
writeQuery
writeFragment
These methods are described in detail below.
Important: You should call these methods on your app's
ApolloClient
object, not directly on the cache. By doing so, theApolloClient
object broadcasts cache changes to your entire app, which enables automatic UI updates. If you call these methods directly on the cache instead, changes are not broadcast.
All code samples below assume that you have initialized an instance of ApolloClient
and that you have imported the gql
tag from graphql-tag
.
readQuery
The readQuery
method enables you to run GraphQL queries directly on your
cache.
If your cache contains all of the data necessary to fulfill a specified query,
readQuery
returns a data object in the shape of your query, just like a GraphQL
server does.
If your cache doesn't contain all of the data necessary to fulfill a specified
query, readQuery
throws an error. It never attempts to fetch data from a remote
server.
Pass readQuery
a GraphQL query string like so:
1const { todo } = client.readQuery({
2 query: gql`
3 query ReadTodo {
4 todo(id: 5) {
5 id
6 text
7 completed
8 }
9 }
10 `,
11});
You can provide GraphQL variables to readQuery
like so:
1const { todo } = client.readQuery({
2 query: gql`
3 query ReadTodo($id: Int!) {
4 todo(id: $id) {
5 id
6 text
7 completed
8 }
9 }
10 `,
11 variables: {
12 id: 5,
13 },
14});
Do not modify the return value of
readQuery
. The same object might be returned to multiple components. To update data in the cache, instead create a replacement object and pass it towriteQuery
.
readFragment
The readFragment
method enables you to read data from any normalized cache
object that was stored as part of any query result. Unlike readQuery
, calls to
readFragment
do not need to conform to the structure of one of your data graph's supported queries.
Here's an example:
1const todo = client.readFragment({
2 id: ..., // `id` is any id that could be returned by `dataIdFromObject`.
3 fragment: gql`
4 fragment myTodo on Todo {
5 id
6 text
7 completed
8 }
9 `,
10});
The first argument, id
, is the unique identifier
that was assigned to the object you want to read from the cache. This should match
the value that your dataIdFromObject
function assigned to the object when it was
stored.
For example, let's say you initialize ApolloClient
like so:
1const client = new ApolloClient({
2 ...,
3 cache: new InMemoryCache({
4 ...,
5 dataIdFromObject: object => object.id,
6 }),
7});
If a previously executed query cached a Todo
object with an id
of 5
, you can
read that object from your cache with the following readFragment
call:
1const todo = client.readFragment({
2 id: '5',
3 fragment: gql`
4 fragment myTodo on Todo {
5 id
6 text
7 completed
8 }
9 `,
10});
In the example above, if a Todo
object with an id
of 5
is not in the cache,
readFragment
returns null
. If the Todo
object is in the cache but it's
missing either a text
or completed
field, readFragment
throws an error.
writeQuery
and writeFragment
In addition to reading arbitrary data from the Apollo Client cache, you can
write arbitrary data to the cache with the writeQuery
and writeFragment
methods.
Any changes you make to cached data with
writeQuery
andwriteFragment
are not pushed to your GraphQL server. If you reload your environment, these changes will disappear.
These methods have the same signature as their read
counterparts, except they
require an additional data
variable.
For example, the following call to writeFragment
locally updates the completed
flag for a Todo
object with an id
of 5
:
1client.writeFragment({
2 id: '5',
3 fragment: gql`
4 fragment myTodo on Todo {
5 completed
6 }
7 `,
8 data: {
9 completed: true,
10 },
11});
All subscribers to the Apollo Client cache see this change and update your application's UI accordingly.
As another example, you can combine readQuery
and writeQuery
to add a new Todo
item to your cached to-do list:
1const query = gql`
2 query MyTodoAppQuery {
3 todos {
4 id
5 text
6 completed
7 }
8 }
9`;
10
11// Get the current to-do list
12const data = client.readQuery({ query });
13
14const myNewTodo = {
15 id: '6',
16 text: 'Start using Apollo Client.',
17 completed: false,
18 __typename: 'Todo',
19};
20
21// Write back to the to-do list and include the new item
22client.writeQuery({
23 query,
24 data: {
25 todos: [...data.todos, myNewTodo],
26 },
27});
Recipes
Here are some common situations where you would need to access the cache directly. If you're manipulating the cache in an interesting way and would like your example to be featured, please send in a pull request!
Bypassing the cache
Sometimes it makes sense to not use the cache for a specific operation. This can be done using the no-cache
fetchPolicy
. The no-cache
policy does not write to the cache with the response. This may be useful for sensitive data like passwords that you don’t want to keep in the cache.
Updating after a mutation
In some cases, just using dataIdFromObject
is not enough for your application UI to update correctly. For example, if you want to add something to a list of objects without refetching the entire list, or if there are some objects that to which you can't assign an object identifier, Apollo Client cannot update existing queries for you. Read on to learn about the other tools at your disposal.
refetchQueries
is the simplest way of updating the cache. With refetchQueries
you can specify one or more queries that you want to run after a mutation is completed in order to refetch the parts of the store that may have been affected by the mutation:
1mutate({
2 //... insert comment mutation
3 refetchQueries: [{
4 query: gql`
5 query UpdateCache($repoName: String!) {
6 entry(repoFullName: $repoName) {
7 id
8 comments {
9 postedBy {
10 login
11 html_url
12 }
13 createdAt
14 content
15 }
16 }
17 }
18 `,
19 variables: { repoName: 'apollographql/apollo-client' },
20 }],
21})
Please note that if you call refetchQueries
with an array of strings, then Apollo Client will look for any previously called queries that have the same names as the provided strings. It will then refetch those queries with their current variables.
A very common way of using refetchQueries
is to import queries defined for other components to make sure that those components will be updated:
1import RepoCommentsQuery from '../queries/RepoCommentsQuery';
2
3mutate({
4 //... insert comment mutation
5 refetchQueries: [{
6 query: RepoCommentsQuery,
7 variables: { repoFullName: 'apollographql/apollo-client' },
8 }],
9})
Using update
gives you full control over the cache, allowing you to make changes to your data model in response to a mutation in any way you like. update
is the recommended way of updating the cache after a query. It is explained in full here.
1import CommentAppQuery from '../queries/CommentAppQuery';
2
3const SUBMIT_COMMENT_MUTATION = gql`
4 mutation SubmitComment($repoFullName: String!, $commentContent: String!) {
5 submitComment(
6 repoFullName: $repoFullName
7 commentContent: $commentContent
8 ) {
9 postedBy {
10 login
11 html_url
12 }
13 createdAt
14 content
15 }
16 }
17`;
18
19const CommentsPageWithMutations = () => (
20 <Mutation mutation={SUBMIT_COMMENT_MUTATION}>
21 {mutate => {
22 <AddComment
23 submit={({ repoFullName, commentContent }) =>
24 mutate({
25 variables: { repoFullName, commentContent },
26 update: (store, { data: { submitComment } }) => {
27 // Read the data from our cache for this query.
28 const data = store.readQuery({ query: CommentAppQuery });
29 // Add our comment from the mutation to the end.
30 data.comments.push(submitComment);
31 // Write our data back to the cache.
32 store.writeQuery({ query: CommentAppQuery, data });
33 }
34 })
35 }
36 />;
37 }}
38 </Mutation>
39);
Incremental loading: fetchMore
fetchMore
can be used to update the result of a query based on the data returned by another query. Most often, it is used to handle infinite-scroll pagination or other situations where you are loading more data when you already have some.
In our GitHunt example, we have a paginated feed that displays a list of GitHub repositories. When we hit the "Load More" button, we don't want Apollo Client to throw away the repository information it has already loaded. Instead, it should just append the newly loaded repositories to the list that Apollo Client already has in the store. With this update, our UI component should re-render and show us all of the available repositories.
Let's see how to do that with the fetchMore
method on a query:
1const FEED_QUERY = gql`
2 query Feed($type: FeedType!, $offset: Int, $limit: Int) {
3 currentUser {
4 login
5 }
6 feed(type: $type, offset: $offset, limit: $limit) {
7 id
8 # ...
9 }
10 }
11`;
12
13const FeedWithData = ({ match }) => (
14 <Query
15 query={FEED_QUERY}
16 variables={{
17 type: match.params.type.toUpperCase() || "TOP",
18 offset: 0,
19 limit: 10
20 }}
21 fetchPolicy="cache-and-network"
22 >
23 {({ data, fetchMore }) => (
24 <Feed
25 entries={data.feed || []}
26 onLoadMore={() =>
27 fetchMore({
28 variables: {
29 offset: data.feed.length
30 },
31 updateQuery: (prev, { fetchMoreResult }) => {
32 if (!fetchMoreResult) return prev;
33 return Object.assign({}, prev, {
34 feed: [...prev.feed, ...fetchMoreResult.feed]
35 });
36 }
37 })
38 }
39 />
40 )}
41 </Query>
42);
The fetchMore
method takes a map of variables
to be sent with the new query. Here, we're setting the offset to feed.length
so that we fetch items that aren't already displayed on the feed. This variable map is merged with the one that's been specified for the query associated with the component. This means that other variables, e.g. the limit
variable, will have the same value as they do within the component query.
It can also take a query
named argument, which can be a GraphQL document containing a query that will be fetched in order to fetch more information; we refer to this as the fetchMore
query. By default, the fetchMore
query is the query associated with the container, in this case the FEED_QUERY
.
When we call fetchMore
, Apollo Client will fire the fetchMore
query and use the logic in the updateQuery
option to incorporate that into the original result. The named argument updateQuery
should be a function that takes the previous result of the query associated with your component (i.e. FEED_QUERY
in this case) and the information returned by the fetchMore
query and return a combination of the two.
Here, the fetchMore
query is the same as the query associated with the component. Our updateQuery
takes the new feed items returned and just appends them onto the feed items that we'd asked for previously. With this, the UI will update and the feed will contain the next page of items!
Although fetchMore
is often used for pagination, there are many other cases in which it is applicable. For example, suppose you have a list of items (say, a collaborative todo list) and you have a way to fetch items that have been updated after a certain time. Then, you don't have to refetch the whole todo list to get updates: you can just incorporate the newly added items with fetchMore
, as long as your updateQuery
function correctly merges the new results.
The @connection
directive
Fundamentally, paginated queries are the same as any other query with the exception that calls to fetchMore
update the same cache key. Since these queries are cached by both the initial query and their parameters, a problem arises when later retrieving or updating paginated queries in the cache. We don’t care about pagination arguments such as limits, offsets, or cursors outside of the need to fetchMore
, nor do we want to provide them simply for accessing cached data.
To solve this Apollo Client 1.6 introduced the @connection
directive to specify a custom store key for results. A connection allows us to set the cache key for a field and to filter which arguments actually alter the query.
To use the @connection
directive, simply add the directive to the segment of the query you want a custom store key for and provide the key
parameter to specify the store key. In addition to the key
parameter, you can also include the optional filter
parameter, which takes an array of query argument names to include in the generated custom store key.
1const query = gql`
2 query Feed($type: FeedType!, $offset: Int, $limit: Int) {
3 feed(type: $type, offset: $offset, limit: $limit) @connection(key: "feed", filter: ["type"]) {
4 ...FeedEntry
5 }
6 }
7`
With the above query, even with multiple fetchMore
s, the results of each feed update will always result in the feed
key in the store being updated with the latest accumulated values. In this example, we also use the @connection
directive's optional filter
argument to include the type
query argument in the store key, which results in multiple store values that accumulate queries from each type of feed.
Now that we have a stable store key, we can easily use writeQuery
to perform a store update, in this case clearing out the feed.
1client.writeQuery({
2 query: gql`
3 query Feed($type: FeedType!) {
4 feed(type: $type) @connection(key: "feed", filter: ["type"]) {
5 id
6 }
7 }
8 `,
9 variables: {
10 type: "top",
11 },
12 data: {
13 feed: [],
14 },
15});
Note that because we are only using the type
argument in the store key, we don't have to provide offset
or limit
.
Cache redirects with cacheRedirects
In some cases, a query requests data that already exists in the client store under a different key. A very common example of this is when your UI has a list view and a detail view that both use the same data. The list view might run the following query:
1query ListView {
2 books {
3 id
4 title
5 abstract
6 }
7}
When a specific book is selected, the detail view displays an individual item using this query:
1query DetailView {
2 book(id: $id) {
3 id
4 title
5 abstract
6 }
7}
Note: The data returned by the list query has to include all the data the specific query needs. If the specific book query fetches a field that the list query doesn't return Apollo Client cannot return the data from the cache.
We know that the data is most likely already in the client cache, but because it's requested with a different query, Apollo Client doesn't know that. In order to tell Apollo Client where to look for the data, we can define custom resolvers:
1import { InMemoryCache } from 'apollo-cache-inmemory';
2
3const cache = new InMemoryCache({
4 cacheRedirects: {
5 Query: {
6 book: (_, args, { getCacheKey }) =>
7 getCacheKey({ __typename: 'Book', id: args.id })
8 },
9 },
10});
Note: This'll also work with custom
dataIdFromObject
methods as long as you use the same one.
Apollo Client will use the ID returned by the custom resolver to look up the item in its cache. getCacheKey
is passed inside the third argument to the resolver to generate the key of the object based on its __typename
and id
.
To figure out what you should put in the __typename
property run one of the queries in GraphiQL and get the __typename
field:
1query ListView {
2 books {
3 __typename
4 }
5}
6
7# or
8
9query DetailView {
10 book(id: $id) {
11 __typename
12 }
13}
The value that's returned (the name of your type) is what you need to put into the __typename
property.
It is also possible to return a list of IDs:
1cacheRedirects: {
2 Query: {
3 books: (_, args, { getCacheKey }) =>
4 args.ids.map(id =>
5 getCacheKey({ __typename: 'Book', id: id }))
6 }
7}
Resetting the store
Sometimes, you may want to reset the store entirely, such as when a user logs out. To accomplish this, use client.resetStore
to clear out your Apollo cache. Since client.resetStore
also refetches any of your active queries for you, it is asynchronous.
1export default withApollo(graphql(PROFILE_QUERY, {
2 props: ({ data: { loading, currentUser }, ownProps: { client }}) => ({
3 loading,
4 currentUser,
5 resetOnLogout: async () => client.resetStore(),
6 }),
7})(Profile));
To register a callback function to be executed after the store has been reset, call client.onResetStore
and pass in your callback. If you would like to register multiple callbacks, simply call client.onResetStore
again. All of your callbacks will be pushed into an array and executed concurrently.
In this example, we're using client.onResetStore
to write our default values to the cache for apollo-link-state
. This is necessary if you're using apollo-link-state
for local state management and calling client.resetStore
anywhere in your application.
1import { ApolloClient } from 'apollo-client';
2import { InMemoryCache } from 'apollo-cache-inmemory';
3import { withClientState } from 'apollo-link-state';
4
5import { resolvers, defaults } from './resolvers';
6
7const cache = new InMemoryCache();
8const stateLink = withClientState({ cache, resolvers, defaults });
9
10const client = new ApolloClient({
11 cache,
12 link: stateLink,
13});
14
15client.onResetStore(stateLink.writeDefaults);
You can also call client.onResetStore
from your React components. This can be useful if you would like to force your UI to rerender after the store has been reset.
If you would like to unsubscribe your callbacks from resetStore, use the return value of client.onResetStore
for your unsubscribe function.
1import { withApollo } from "react-apollo";
2
3export class Foo extends Component {
4 constructor(props) {
5 super(props);
6 this.unsubscribe = props.client.onResetStore(
7 () => this.setState({ reset: false })
8 );
9 this.state = { reset: false };
10 }
11 componentDidUnmount() {
12 this.unsubscribe();
13 }
14 render() {
15 return this.state.reset ? <div /> : <span />
16 }
17}
18
19export default withApollo(Foo);
If you want to clear the store but don't want to refetch active queries, use
client.clearStore()
instead of client.resetStore()
.
Server side rendering
First, you will need to initialize an InMemoryCache
on the server and create an instance of ApolloClient
. In the initial serialized HTML payload from the server, you should include a script tag that extracts the data from the cache. (The .replace()
is necessary to prevent script injection attacks)
1`<script>
2 window.__APOLLO_STATE__=${JSON.stringify(cache.extract()).replace(/</g, '\\u003c')}
3</script>`
On the client, you can rehydrate the cache using the initial data passed from the server:
1cache: new Cache().restore(window.__APOLLO_STATE__)
If you would like to learn more about server side rendering, please check out our more in depth guide here.
Cache persistence
If you would like to persist and rehydrate your Apollo Cache from a storage provider like AsyncStorage
or localStorage
, you can use apollo-cache-persist
. apollo-cache-persist
works with all Apollo caches, including InMemoryCache
& Hermes
, and a variety of different storage providers.
To get started, simply pass your Apollo Cache and a storage provider to persistCache
. By default, the contents of your Apollo Cache will be immediately restored asynchronously, and persisted upon every write to the cache with a short configurable debounce interval.
Note: The
persistCache
method is async and returns aPromise
.
1import { AsyncStorage } from 'react-native';
2import { InMemoryCache } from 'apollo-cache-inmemory';
3import { persistCache } from 'apollo-cache-persist';
4
5const cache = new InMemoryCache();
6
7persistCache({
8 cache,
9 storage: AsyncStorage,
10}).then(() => {
11 // Continue setting up Apollo as usual.
12})
For more advanced usage, such as persisting the cache when the app is in the background, and additional configuration options, please check the README of apollo-cache-persist
.