class InMemoryCache

API reference


Methods of the InMemoryCache class (the cache used by almost every instance of ApolloClient ) are documented here.

Before reading about individual methods, see Caching in Apollo Client .

readQuery

Executes a GraphQL query directly against the cache and returns its result (or null if the query cannot be fulfilled):

JavaScript
1// Query a cached Todo object with id 5
2const { todo } = cache.readQuery({
3  query: gql`
4    query ReadTodo {
5      todo(id: 5) {
6        id
7        text
8        completed
9      }
10    }
11  `,
12});

For usage instructions, see Interacting with cached data: readQuery .

Accepts the following parameters:

Name /
Type
Description
options
Object
Required. Provides configuration options for the query, including the actual query to execute.Supported fields are listed below.
optimistic
Boolean
If true, readQuery returns optimistic results.The default value is false.

Options

Name /
Type
Description
query
DocumentNode
Required. The GraphQL query to execute, created by wrapping a query string in the gql template literal.
variables
Object
A map of any GraphQL variable names and values required by query.
id
String
The root id to use for the query.The default value is ROOT_QUERY, which is the ID of the root query object.By specifying the ID of another cached object, you can query arbitrary cached data without conforming to the structure of your schema's supported queries. This enables readQuery to behave similarly to readFragment .
canonizeResults
Boolean
⚠️ Deprecated: Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
If true, result objects read from the cache will be canonized, which means deeply-equal objects will also be === (literally the same object), allowing much more efficient comparison of past/present results.The default value is false.

Signature

TypeScript
src/cache/core/cache.ts
1readQuery<QueryType, TVariables = any>(
2  options: DataProxy.Query<TVariables>,
3  optimistic: boolean = false,
4): QueryType | null

writeQuery

Writes data to the cache in the shape of a provided GraphQL query. Returns a Reference to the written object or undefined if the write failed.

JavaScript
1// Create or modify a cached Todo object with id 5
2cache.writeQuery({
3  query: gql`
4    query ReadTodo($id: ID!) {
5      todo(id: $id) {
6        id
7        text
8        completed
9      }
10    }
11  `,
12  data: {
13    todo: {
14      __typename: 'Todo',
15      id: 5,
16      text: 'Buy grapes 🍇',
17      completed: false
18    },
19  },
20  variables: {
21    id: 5
22  }
23});

For usage instructions, see Interacting with cached data: writeQuery .

Takes an options object as a parameter. Supported fields of this object are described below.

Options

Name /
Type
Description
query
DocumentNode
Required. The GraphQL query that defines the shape of the data to write. Created by wrapping a query string in the gql template literal.
data
Object
Required. The data to write to the cache. This object's fields must conform to the shape defined by query.
variables
Object
A map of any GraphQL variable names and values required by query.
id
String
The id of the root object to use with query.The default value is ROOT_QUERY, which is the ID of the root query object.By specifying the ID of another cached object, you can modify arbitrary cached data without conforming to the structure of your schema's supported queries. This enables writeQuery to behave similarly to writeFragment .
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's modified by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.
overwrite
Boolean
If true, ignore existing cache data when calling merge functions, allowing incoming data to replace existing data, without warnings about data loss.The default value is false.

Signature

TypeScript
src/cache/core/cache.ts
1writeQuery<TData = any, TVariables = any>(
2  options: Cache.WriteQueryOptions<TData, TVariables>,
3): Reference | undefined

updateQuerySince 3.5

Fetches data from the cache in the shape of a provided GraphQL query, then updates that cached data according to a provided update function.

Returns the updated result or null if the update failed.

JavaScript
1// Fetches a Todo object with id 5 and flips its `completed` boolean
2cache.updateQuery({ // options object
3  query: gql`
4    query ReadTodo($id: ID!) {
5      todo(id: $id) {
6        id
7        text
8        completed
9      }
10    }
11  `,
12  variables: {
13    id: 5
14  }
15}, (data) => ({ // update function
16  todo: {
17    ...data.todo,
18    completed: !data.todo.completed
19  }
20}));

Takes an options object and an update function as parameters (both described below).

Options

Name /
Type
Description
query
DocumentNode
Required. The GraphQL query that defines the shape of the data to fetch. Created by wrapping a query string in the gql template literal.
variables
Object
A map of any GraphQL variable names and values required by query.
id
String
The id of the root object to use with query.The default value is ROOT_QUERY, which is the ID of the root query object.By specifying the ID of another cached object, you can modify arbitrary cached data without conforming to the structure of your schema's supported queries. This enables updateQuery to behave similarly to updateFragment .
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's modified by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.
overwrite
Boolean
If true, ignore existing cache data when calling merge functions, allowing incoming data to replace existing data, without warnings about data loss.The default value is false.

updateQuery update function

The update function of updateQuery takes a query's current cached value and returns the value that should replace it (or undefined if no change should be made).

The returned value is automatically passed to writeQuery , which modifies the cached data.

Please note the update function has to calculate the new value in an immutable way. You can read more about immutable updates in the React documentation .

Signature

TypeScript
src/cache/core/cache.ts
1public updateQuery<TData = any, TVariables = any>(
2  options: Cache.UpdateQueryOptions<TData, TVariables>,
3  update: (data: TData | null) => TData | null | void,
4): TData | null

readFragment

Reads data from the cache in the shape of a provided GraphQL fragment:

JavaScript
1const todo = cache.readFragment({
2  id: '5', // The value of the to-do item's unique identifier
3  fragment: gql`
4    fragment MyTodo on Todo {
5      id
6      text
7      completed
8    }
9  `,
10});

Returns the requested data or null if data is not available in the cache.

For usage instructions, see Interacting with cached data: readFragment .

Accepts the following parameters:

Name /
Type
Description
options
Object
Required. Provides configuration options, including the actual fragment to use.Supported fields are listed below.
optimistic
Boolean
If true, readFragment returns optimistic results.The default value is false.

Options

Name /
Type
Description
id
String
Required. The ID of the cached object that this call is reading a fragment of.If the cache does not contain an object with the specified ID, readFragment returns null.
fragment
DocumentNode
Required. A GraphQL document created with the gql template literal tag that includes the fragment to read.If the document includes more than one fragment, you must also provide fragmentName to indicate which to use.
fragmentName
String
The name of the fragment defined in the fragment document to use in the call.You don't need to provide this value if the fragment document includes only one fragment.
variables
Object
A map of any GraphQL variable names and values required by fragment.
canonizeResults
Boolean
⚠️ Deprecated: Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
If true, result objects read from the cache will be canonized, which means deeply-equal objects will also be === (literally the same object), allowing much more efficient comparison of past/present results.The default value is false.

Signature

TypeScript
src/cache/core/cache.ts
1readFragment<FragmentType, TVariables = any>(
2  options: DataProxy.Fragment<TVariables>,
3  optimistic: boolean = false,
4): FragmentType | null

writeFragment

Writes data to the cache in the shape of the provided GraphQL fragment. Returns a Reference to the written object or undefined if the write failed.

JavaScript
1client.writeFragment({
2  id: 'Todo:5',
3  fragment: gql`
4    fragment MyTodo on Todo {
5      completed
6    }
7  `,
8  data: {
9    completed: true,
10  },
11});

For usage instructions, see Interacting with cached data: writeFragment .

Takes an options object as a parameter. Supported fields of this object are described below.

Options

Name /
Type
Description
id
String
Required. The ID of the cached object that this call is writing a fragment to.If the cache does not contain an object with the specified ID, writeFragment returns null.
fragment
DocumentNode
Required. A GraphQL document created with the gql template literal tag that includes the fragment to write.If the document includes more than one fragment, you must also provide fragmentName to indicate which to use.
data
Object
Required. The data to write to the cache. This object's fields must conform to the shape defined by fragment.
fragmentName
String
The name of the fragment defined in the fragment document to use in the call.You don't need to provide this value if the fragment document includes only one fragment.
variables
Object
A map of any GraphQL variable names and values required by fragment.
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's modified by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.
overwrite
Boolean
If true, ignore existing cache data when calling merge functions, allowing incoming data to replace existing data, without warnings about data loss.The default value is false.

Signature

TypeScript
src/cache/core/cache.ts
1writeFragment<TData = any, TVariables = any>(
2  options: Cache.WriteFragmentOptions<TData, TVariables>,
3): Reference | undefined

watchFragment Since 3.10.0

Watches the cache store of the fragment according to the options specified and returns an Observable. We can subscribe to this Observable and receive updated results through an observer when the cache store changes.

You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are reading. If you pass in a document with multiple fragments then you must also specify a fragmentName.

Signature

TypeScript
1watchFragment<TFragmentData, TVariables>(
2  options: WatchFragmentOptions<TFragmentData, TVariables>
3): Observable<WatchFragmentResult<TFragmentData>>

Parameters

Name / Type
Description
options WatchFragmentOptions<TFragmentData, TVariables>

An object of type WatchFragmentOptions that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.

Result

Observable<WatchFragmentResult<TFragmentData>>

updateFragmentSince 3.5

Fetches data from the cache in the shape of a provided GraphQL fragment, then updates that cached data according to a provided update function.

Returns the updated result or null if the update failed.

JavaScript
1// Fetches a Todo object with id 5 and sets its `completed` boolean to true
2const todo = cache.updateFragment({ // options object
3  id: '5', // The value of the to-do item's unique identifier
4  fragment: gql`
5    fragment MyTodo on Todo {
6      completed
7    }
8  `,
9}, (data) => ({ ...data, completed: true }) // update function
10);

Takes an options object and an update function as parameters (both described below).

Options

Name /
Type
Description
id
String
Required. The ID of the cached object that this call is reading a fragment of.If the cache does not contain an object with the specified ID, updateFragment returns null.
fragment
DocumentNode
Required. A GraphQL document created with the gql template literal tag that includes the fragment to read.If the document includes more than one fragment, you must also provide fragmentName to indicate which to use.
fragmentName
String
The name of the fragment defined in the fragment document to use in the call.You don't need to provide this value if the fragment document includes only one fragment.
variables
Object
A map of any GraphQL variable names and values required by fragment.
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's modified by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.
overwrite
Boolean
If true, ignore existing cache data when calling merge functions, allowing incoming data to replace existing data, without warnings about data loss.The default value is false.

updateFragment update function

The update function of updateFragment takes a fragment's current cached value and returns the value that should replace it (or undefined if no change should be made).

The returned value is automatically passed to writeFragment , which modifies the cached data.

Please note the update function has to calculate the new value in an immutable way. You can read more about immutable updates in the React documentation .

Signature

TypeScript
src/cache/core/cache.ts
1public updateFragment<TData = any, TVariables = any>(
2  options: Cache.UpdateFragmentOptions<TData, TVariables>,
3  update: (data: TData | null) => TData | null | void,
4): TData | null

identify

Returns the canonical ID for a specified cached object.

You can provide either an object or an object reference to this function:

  • If you provide an object, identify returns the object's string-based ID (e.g., Car:1).

  • If you provide a reference, identify return the reference's __ref ID string.

For usage instructions, see Interacting with cached data: Identify cached entities .

Accepts the following parameters:

Name /
Type
Description
object
StoreObject or Reference
Required. The cached object (or object reference) to obtain the canonical ID for.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1identify(object: StoreObject | Reference): string | undefined

modify

Modifies one or more field values of a cached object. Must provide a modifier function for each field to modify. A modifier function takes a cached field's current value and returns the value that should replace it.

Returns true if the cache was modified successfully and false otherwise.

For usage instructions, see Using cache.modify .

Takes an options object as a parameter. Supported fields of this object are described below.

Options

Name /
Type
Description
fields
Object
Required. A map that specifies the modifier function to call for each modified field of the cached object.See Modifier function API below.
id
string
The ID of the cached object to modify.The default value is ROOT_QUERY (the ID of the root query singleton object).
optimistic
Boolean
If true, also modifies the optimistically cached values for included fields.The default value is false.
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's modified by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.

Modifier function API

A modifier function takes a cached field's current value and returns the value that should replace it, or the DELETE sentinel object to delete the field entirely.

The first parameter passed to a modifier function is the current cached value of the field being modified.

The second parameter is a helper object that contains the following utilities:

Name /
Type
Description
fieldName
String
The name of the field being modified.
storeFieldName
String
The full key for the field used internally, including serialized key arguments.
readField
Function
A helper function for reading other fields on the object passed to the modifier function as the first parameter.
canRead
Function
A helper function that returns true for non-normalized StoreObjects and non-dangling References. This indicates that readField(name, objOrRef) has a chance of working.Useful for filtering dangling references out of lists.
isReference
Function
A helper function that returns true if a particular object is a reference to a cached entity.
DELETE
Object
A sentinel object that you can return from a modifier function to indicate that the field should be deleted entirely.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1modify(options: Cache.ModifyOptions): boolean

gc

Performs garbage collection of unreachable normalized objects in the cache:

JavaScript
1cache.gc();

Returns an array containing the IDs of all objects removed from the cache.

For usage instructions, see cache.gc .

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1gc()

evict

Either removes a normalized object from the cache or removes a specific field from a normalized object in the cache:

JavaScript
1cache.evict({ id: 'my-object-id', fieldName: 'myFieldName' });

Returns true if data was removed from the cache, false otherwise.

For usage instructions, see cache.evict .

Takes an options object as a parameter. Supported fields of this object are described below.

Options

Name /
Type
Description
id
String
The ID of the cached object to remove (or remove a field from).The default value is ROOT_QUERY, which is the ID of the root query object.
fieldName
String
The name of the field to remove from the cached object.Omit this option if you are removing the entire object.
args
Record<string, any>
If provided with fieldName, only instances of the field with the specified arguments are removed from the cache.Otherwise, all instances of the field are removed for the cached object.
broadcast
Boolean
If true, automatically refresh all active queries that depend on at least one field that's removed by this call. If false, silences the broadcast of cache updates and prevents automatic query refresh.The default value is true.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1evict(options: Cache.EvictOptions): boolean

extract

Returns a serialized representation of the cache's current contents as a NormalizedCacheObject.

Accepts the following parameters:

Name /
Type
Description
optimistic
Boolean
If true, optimistic data is included in the serialization.The default value is false.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1extract(optimistic: boolean = false): NormalizedCacheObject

restore

Restores the cache's state from a serialized NormalizedCacheObject (such as one returned by extract ). This removes all existing data from the cache.

Returns the InMemoryCache instance it's called on.

Accepts the following parameters:

Name /
Type
Description
data
NormalizedCacheObject
Required. The serialization to restore the cache from.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1restore(data: NormalizedCacheObject): this

makeVar

Creates a reactive variable with an optional initial value:

JavaScript
1const cartItems = makeVar([]);

Returns the reactive variable function you use to read or modify the variable's value.

For usage instructions, see Reactive variables .

Accepts the following parameters:

Name /
Type
Description
value
Any
The reactive variable's initial value.

Signature

TypeScript
src/cache/inmemory/inMemoryCache.ts
1makeVar<T>(value: T): ReactiveVar<T>