class InMemoryCache
API reference
Methods of the InMemoryCache
class (the cache used by almost every instance of ApolloClient
Before reading about individual methods, see
readQuery
readQuery
Executes a GraphQL query directly against the cache and returns its result (or null
if the query cannot be fulfilled):
// Query a cached Todo object with id 5const { todo } = cache.readQuery({query: gql`query ReadTodo {todo(id: 5) {idtextcompleted}}`,});
For usage instructions, see readQuery
Accepts the following parameters:
Name / Type | Description |
---|---|
options
| Required. Provides configuration options for the query, including the actual query to execute. Supported fields are listed below. |
optimistic
| If The default value is |
Options
Name / Type | Description |
---|---|
query
| Required. The GraphQL query to execute, created by wrapping a query string in the |
variables
| A map of any GraphQL variable names and values required by |
id
| The root The default value is 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 |
canonizeResults
| ⚠️ Deprecated:
Using If The default value is |
Signature
readQuery<QueryType, TVariables = any>(options: DataProxy.Query<TVariables>,optimistic: boolean = false,): QueryType | null
writeQuery
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.
// Create or modify a cached Todo object with id 5cache.writeQuery({query: gql`query ReadTodo($id: ID!) {todo(id: $id) {idtextcompleted}}`,data: {todo: {__typename: 'Todo',id: 5,text: 'Buy grapes 🍇',completed: false},},variables: {id: 5}});
For usage instructions, see writeQuery
Takes an options
object as a parameter. Supported fields of this object are described below.
Options
Name / Type | Description |
---|---|
query
| Required. The GraphQL query that defines the shape of the data to write. Created by wrapping a query string in the |
data
| Required. The data to write to the cache. This object's fields must conform to the shape defined by |
variables
| A map of any GraphQL variable names and values required by |
id
| The The default value is 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 |
broadcast
| If The default value is |
overwrite
| If The default value is |
Signature
writeQuery<TData = any, TVariables = any>(options: Cache.WriteQueryOptions<TData, TVariables>,): Reference | undefined
updateQuery
Since 3.5
updateQuery
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.
// Fetches a Todo object with id 5 and flips its `completed` booleancache.updateQuery({ // options objectquery: gql`query ReadTodo($id: ID!) {todo(id: $id) {idtextcompleted}}`,variables: {id: 5}}, (data) => ({ // update functiontodo: {...data.todo,completed: !data.todo.completed}}));
Takes an options
object and an update function as parameters (both described below).
Options
Name / Type | Description |
---|---|
query
| Required. The GraphQL query that defines the shape of the data to fetch. Created by wrapping a query string in the |
variables
| A map of any GraphQL variable names and values required by |
id
| The The default value is 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 |
broadcast
| If The default value is |
overwrite
| If The default value is |
updateQuery
update function
updateQuery
update functionThe 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
Please note the update
function has to calculate the new value in an immutable way. You can read more about immutable updates in the
Signature
public updateQuery<TData = any, TVariables = any>(options: Cache.UpdateQueryOptions<TData, TVariables>,update: (data: TData | null) => TData | null | void,): TData | null
readFragment
readFragment
Reads data from the cache in the shape of a provided GraphQL fragment:
const todo = cache.readFragment({id: '5', // The value of the to-do item's unique identifierfragment: gql`fragment MyTodo on Todo {idtextcompleted}`,});
Returns the requested data or null
if data is not available in the cache.
For usage instructions, see readFragment
Accepts the following parameters:
Name / Type | Description |
---|---|
options
| Required. Provides configuration options, including the actual fragment to use. Supported fields are listed below. |
optimistic
| If The default value is |
Options
Name / Type | Description |
---|---|
id
| 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, |
fragment
| Required. A GraphQL document created with the If the document includes more than one fragment, you must also provide |
fragmentName
| The name of the fragment defined in the You don't need to provide this value if the |
variables
| A map of any GraphQL variable names and values required by |
canonizeResults
| ⚠️ Deprecated:
Using If The default value is |
Signature
readFragment<FragmentType, TVariables = any>(options: DataProxy.Fragment<TVariables>,optimistic: boolean = false,): FragmentType | null
writeFragment
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.
client.writeFragment({id: 'Todo:5',fragment: gql`fragment MyTodo on Todo {completed}`,data: {completed: true,},});
For usage instructions, see writeFragment
Takes an options
object as a parameter. Supported fields of this object are described below.
Options
Name / Type | Description |
---|---|
id
| 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, |
fragment
| Required. A GraphQL document created with the If the document includes more than one fragment, you must also provide |
data
| Required. The data to write to the cache. This object's fields must conform to the shape defined by |
fragmentName
| The name of the fragment defined in the You don't need to provide this value if the |
variables
| A map of any GraphQL variable names and values required by |
broadcast
| If The default value is |
overwrite
| If The default value is |
Signature
writeFragment<TData = any, TVariables = any>(options: Cache.WriteFragmentOptions<TData, TVariables>,): Reference | undefined
updateFragment
Since 3.5
updateFragment
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.
// Fetches a Todo object with id 5 and sets its `completed` boolean to trueconst todo = cache.updateFragment({ // options objectid: '5', // The value of the to-do item's unique identifierfragment: gql`fragment MyTodo on Todo {completed}`,}, (data) => ({ ...data, completed: true }) // update function);
Takes an options
object and an update function as parameters (both described below).
Options
Name / Type | Description |
---|---|
id
| 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, |
fragment
| Required. A GraphQL document created with the If the document includes more than one fragment, you must also provide |
fragmentName
| The name of the fragment defined in the You don't need to provide this value if the |
variables
| A map of any GraphQL variable names and values required by |
broadcast
| If The default value is |
overwrite
| If The default value is |
updateFragment
update function
updateFragment
update functionThe 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
Please note the update
function has to calculate the new value in an immutable way. You can read more about immutable updates in the
Signature
public updateFragment<TData = any, TVariables = any>(options: Cache.UpdateFragmentOptions<TData, TVariables>,update: (data: TData | null) => TData | null | void,): TData | null
identify
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
Accepts the following parameters:
Name / Type | Description |
---|---|
object
| Required. The cached object (or object reference) to obtain the canonical ID for. |
Signature
identify(object: StoreObject | Reference): string | undefined
modify
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 cache.modify
Takes an options
object as a parameter. Supported fields of this object are described below.
Options
Name / Type | Description |
---|---|
fields
| Required. A map that specifies the modifier function to call for each modified field of the cached object. See |
id
| The ID of the cached object to modify. The default value is |
optimistic
| If The default value is |
broadcast
| If The default value is |
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
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
| The name of the field being modified. |
storeFieldName
| The full key for the field used internally, including serialized key arguments. |
readField
| A helper function for reading other fields on the object passed to the modifier function as the first parameter. |
canRead
| A helper function that returns Useful for filtering dangling references out of lists. |
isReference
| A helper function that returns |
DELETE
| A sentinel object that you can return from a modifier function to indicate that the field should be deleted entirely. |
Signature
modify(options: Cache.ModifyOptions): boolean
gc
gc
Performs garbage collection of unreachable normalized objects in the cache:
cache.gc();
Returns an array containing the IDs of all objects removed from the cache.
For usage instructions, see cache.gc
Signature
gc()
evict
evict
Either removes a normalized object from the cache or removes a specific field from a normalized object in the cache:
cache.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
| The ID of the cached object to remove (or remove a field from). The default value is |
fieldName
| The name of the field to remove from the cached object. Omit this option if you are removing the entire object. |
args
| If provided with Otherwise, all instances of the field are removed for the cached object. |
broadcast
| If The default value is |
Signature
evict(options: Cache.EvictOptions): boolean
extract
extract
Returns a serialized representation of the cache's current contents as a NormalizedCacheObject
.
Accepts the following parameters:
Name / Type | Description |
---|---|
optimistic
| If The default value is |
Signature
extract(optimistic: boolean = false): NormalizedCacheObject
restore
restore
Restores the cache's state from a serialized NormalizedCacheObject
(such as one returned by extract
Returns the InMemoryCache
instance it's called on.
Accepts the following parameters:
Name / Type | Description |
---|---|
data
| Required. The serialization to restore the cache from. |
Signature
restore(data: NormalizedCacheObject): this
makeVar
makeVar
Creates a reactive variable with an optional initial value:
const cartItems = makeVar([]);
Returns the reactive variable function you use to read or modify the variable's value.
For usage instructions, see
Accepts the following parameters:
Name / Type | Description |
---|---|
value Any | The reactive variable's initial value. |
Signature
makeVar<T>(value: T): ReactiveVar<T>