Apollo Cache: Querying by id

In the cache documentation [1], the docs describe a scenario where “the first time your app queries for a Book object with id 5”.

What does it mean to query a Book with object id 5? Does it mean a query that uses id as a variable like the following:

Query {
  book(id: 5)
}

GraphQL variables don’t necessarily correspond to object fields, so there’s no way in general to know that this is a query for Book:5. Does Apollo assume the id variable is a request for an object with that id?

The docs then say “And each later time your app queries for that same object”. What does it mean to query for the same object? As I understand, Apollo does not know about my GraphQL schema, so it doesn’t know which fields correspond to which objects. So it couldn’t, for instance, return a cached result for a separate query:

Query {
   getBook(id: 5)
}

Does the subsequent query have to be for the same field, i.e. book(id: 5)?

[1] Caching in Apollo Client - Apollo GraphQL Docs

1 Like

I have this similar question after querying for a relay-node with given ID and the inability to get a response on a cache-only fetchPolicy

I don’t know if all query → cache object reference mapping has to be done manually, but here are some ideas you can play with and maybe one of them will help you get your cache working:

  1. First, do you have your keyFields enumerated in your ApolloClient cache configuration? When initializing the client, you need to create a cache configuration that specifies the Book object (for instance), along with it’s key field - otherwise, your Book objects cannot be object-level cached.
  2. If you’re using different queries to fetch Book data, you may need to declare a toReference() callback implementation in the Book object’s read() function supplied in your cache configuration as well.

All of this is documented (somewhat) in the apollo client docs, where you can find examples of what I’m talking about.