docs/source/api/cache/InMemoryCache.mdx
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.
readQueryExecutes 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 5
const { todo } = cache.readQuery({
query: gql`
query ReadTodo {
todo(id: 5) {
id
text
completed
}
}
`,
});
For usage instructions, see Interacting with cached data: readQuery.
Accepts the following parameters:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr class="required"> <td>optionsObject
Required. Provides configuration options for the query, including the actual query to execute.
Supported fields are listed below.
</td> </tr> <tr> <td>optimisticBoolean
If true, readQuery returns optimistic results.
The default value is false.
queryDocumentNode
Required. The GraphQL query to execute, created by wrapping a query string in the gql template literal.
variablesObject
A map of any GraphQL variable names and values required by query.
idString
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.
readQuery<TData = unknown, TVariables = OperationVariables>(
options: Cache.ReadQueryOptions<TData, TVariables>,
optimistic: boolean = false,
): Unmasked<TData> | null
writeQueryWrites 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 5
cache.writeQuery({
query: gql`
query ReadTodo($id: ID!) {
todo(id: $id) {
id
text
completed
}
}
`,
data: {
todo: {
__typename: "Todo",
id: 5,
text: "Buy grapes 🍇",
completed: false,
},
},
variables: {
id: 5,
},
});
For usage instructions, see Interacting with cached data: writeQuery.
Takes an options object as a parameter. Supported fields of this object are described below.
queryDocumentNode
Required. The GraphQL query that defines the shape of the data to write. Created by wrapping a query string in the gql template literal.
dataObject
Required. The data to write to the cache. This object's fields must conform to the shape defined by query.
variablesObject
A map of any GraphQL variable names and values required by query.
idString
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.
broadcastBoolean
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.
overwriteBoolean
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.
writeQuery<TData = unknown, TVariables = OperationVariables>(
options: Cache.WriteQueryOptions<TData, TVariables>,
): Reference | undefined
updateQueryFetches 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` boolean
cache.updateQuery(
// options object
{
query: gql`
query ReadTodo($id: ID!) {
todo(id: $id) {
id
text
completed
}
}
`,
variables: {
id: 5,
},
},
// update function
(data) => ({
todo: {
...data.todo,
completed: !data.todo.completed,
},
})
);
Takes an options object and an update function as parameters (both described below).
queryDocumentNode
Required. The GraphQL query that defines the shape of the data to fetch. Created by wrapping a query string in the gql template literal.
variablesObject
A map of any GraphQL variable names and values required by query.
idString
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.
broadcastBoolean
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.
overwriteBoolean
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 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, 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.
public updateQuery<TData = unknown, TVariables = OperationVariables>(
options: Cache.UpdateQueryOptions<TData, TVariables>,
update: (data: TData | null) => TData | null | void,
): TData | null
readFragmentReads 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 identifier
fragment: gql`
fragment MyTodo on Todo {
id
text
completed
}
`,
});
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:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr class="required"> <td>optionsObject
Required. Provides configuration options, including the actual fragment to use.
Supported fields are listed below.
</td> </tr> <tr> <td>optimisticBoolean
If true, readFragment returns optimistic results.
The default value is false.
idString
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.
fragmentDocumentNode
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.
fragmentNameString
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.
variablesObject
A map of any GraphQL variable names and values required by fragment.
readFragment<TData = unknown, TVariables = OperationVariables>(
options: Cache.ReadFragmentOptions<TData, TVariables>,
optimistic: boolean = false,
): Unmasked<TData> | null
writeFragmentWrites 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 Interacting with cached data: writeFragment.
Takes an options object as a parameter. Supported fields of this object are described below.
idString
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.
fragmentDocumentNode
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.
dataObject
Required. The data to write to the cache. This object's fields must conform to the shape defined by fragment.
fragmentNameString
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.
variablesObject
A map of any GraphQL variable names and values required by fragment.
broadcastBoolean
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.
overwriteBoolean
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.
writeFragment<TData = unknown, TVariables = OperationVariables>(
options: Cache.WriteFragmentOptions<TData, TVariables>,
): Reference | undefined
<FunctionDetails canonicalReference="@apollo/client!ApolloClient#watchFragment:member(1)" headingLevel={2} />
updateFragmentFetches 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 true
const todo = cache.updateFragment(
// options object
{
id: "5", // The value of the to-do item's unique identifier
fragment: gql`
fragment MyTodo on Todo {
completed
}
`,
},
// update function
(data) => ({ ...data, completed: true })
);
Takes an options object and an update function as parameters (both described below).
idString
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.
fragmentDocumentNode
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.
fragmentNameString
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.
variablesObject
A map of any GraphQL variable names and values required by fragment.
broadcastBoolean
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.
overwriteBoolean
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 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, 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.
public updateFragment<TData = unknown, TVariables = OperationVariables>(
options: Cache.UpdateFragmentOptions<TData, TVariables>,
update: (data: TData | null) => TData | null | void,
): TData | null
<FunctionDetails canonicalReference="@apollo/client!InMemoryCache#batch:member(1)" headingLevel={2} result={false} />
identifyReturns the canonical ID for a specified cached object.
You can provide either an object or an object reference to this function:
identify returns the object's string-based ID (e.g., Car:1).identify return the reference's __ref ID string.For usage instructions, see Interacting with cached data: Identify cached entities.
Accepts the following parameters:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr class="required"> <td>objectStoreObject or Reference
Required. The cached object (or object reference) to obtain the canonical ID for.
</td> </tr> </tbody> </table>identify(object: StoreObject | Reference): string | undefined
modifyModifies 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.
fieldsObject
Required. A map that specifies the modifier function to call for each modified field of the cached object.
See Modifier function API below.
</td> </tr> <tr> <td>idstring
The ID of the cached object to modify.
The default value is ROOT_QUERY (the ID of the root query singleton object).
optimisticBoolean
If true, also modifies the optimistically cached values for included fields.
The default value is false.
broadcastBoolean
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.
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:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>fieldNameString
The name of the field being modified.
</td> </tr> <tr> <td>storeFieldNameString
The full key for the field used internally, including serialized key arguments.
</td> </tr> <tr> <td>readFieldFunction
A helper function for reading other fields on the object passed to the modifier function as the first parameter.
</td> </tr> <tr> <td>canReadFunction
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.
</td> </tr> <tr> <td>isReferenceFunction
A helper function that returns true if a particular object is a reference to a cached entity.
DELETEObject
A sentinel object that you can return from a modifier function to indicate that the field should be deleted entirely.
</td> </tr> </tbody> </table>modify(options: Cache.ModifyOptions): boolean
gcPerforms 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.
gc();
evictEither 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.
idString
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.
fieldNameString
The name of the field to remove from the cached object.
Omit this option if you are removing the entire object.
</td> </tr> <tr> <td>argsRecord<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.
</td> </tr> <tr> <td>broadcastBoolean
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.
evict(options: Cache.EvictOptions): boolean
extractReturns a serialized representation of the cache's current contents as a NormalizedCacheObject.
Accepts the following parameters:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>optimisticBoolean
If true, optimistic data is included in the serialization.
The default value is false.
extract(optimistic: boolean = false): NormalizedCacheObject
restoreRestores 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:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr class="required"> <td>dataNormalizedCacheObject
Required. The serialization to restore the cache from.
</td> </tr> </tbody> </table>restore(data: NormalizedCacheObject): this
makeVarCreates 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 Reactive variables.
Accepts the following parameters:
<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>valueAny
</td> <td>The reactive variable's initial value.
</td> </tr> </tbody> </table>makeVar<T>(value: T): ReactiveVar<T>