A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.apollographql.com/docs/react/caching/cache-interaction below:

Website Navigation


Reading and writing data to the cache

You can read and write data directly to the Apollo Client cache, without communicating with your GraphQL server. You can interact with data that you previously fetched from your server, and with data that's only available locally.

Apollo Client supports multiple strategies for interacting with cached data:

You can use whichever combination of strategies and methods are most helpful for your use case.

Bear in mind the difference between fields that contain references to other objects in the cache and fields that contain literal values. References are objects that contain a __ref field—see the example in the caching overview. Modifying a reference will not change the values contained in the object to which the reference points. So avoid updating an object from something like {__ref: '5'} to {__ref: '5', completed: true}.

All code samples below assume that you have initialized an instance of ApolloClient and that you have imported the gql function from @apollo/client. If you haven't, get started.

In a React component, you can access your instance of ApolloClient using ApolloProvider and the useApolloClient hook.

Using GraphQL queries

You can read and write cache data using GraphQL queries that are similar (or even identical) to queries that you execute on your server:

readQuery

The readQuery method enables you to execute a GraphQL query directly on your cache, like so:

If your cache contains data for all of the query's fields, readQuery returns an object that matches the shape of the query.

To successfully execute queries with variables, the field with the specified argument must already be in the cache. In the above example, to get the to-do item with the id of 5, the todo field(s) for id:5 must already be cached. For this example, the cache would need to look something like this:

Otherwise the client treats the data as missing and readQuery returns null. To learn more about how the caching works, checkout the caching overview.

Apollo Client automatically queries for every object's __typename by default, even if you don't include this field in your query string.

Do not modify the returned object directly. The same object might be returned to multiple components. To update cached data safely, see Combining reads and writes.

If the cache is missing data for any of the query's fields, readQuery returns null. It does not attempt to fetch data from your GraphQL server.

The query you provide readQuery can include fields that are not defined in your GraphQL server's schema (i.e., local-only fields).

Prior to Apollo Client 3.3, readQuery threw a MissingFieldError exception to report missing fields. Beginning with Apollo Client 3.3, readQuery always returns null to indicate that fields are missing.

writeQuery

The writeQuery method enables you to write data to your cache in a shape that matches a GraphQL query. It resembles readQuery, except that it requires a data option:

This example creates (or edits) a cached Todo object with ID 5.

Note the following about writeQuery:

Editing existing data

In the example above, if your cache already contains a Todo object with ID 5, writeQuery overwrites the fields that are included in data (other fields are preserved):

If you include a field in query but don't include a value for it in data, the field's current cached value is preserved.

Using GraphQL fragments

You can read and write cache data using GraphQL fragments on any normalized cache object. This provides more "random access" to your cached data than readQuery/writeQuery, which require a complete valid query.

readFragment

This example fetches the same data as the example for readQuery using readFragment instead:

Unlike readQuery, readFragment requires an id option. This option specifies the cache ID for the object in your cache. By default, cache IDs have the format <__typename>:<id> (which is why we provide Todo:5 above). You can customize this ID.

In the example above, readFragment returns null in either of the following cases:

Prior to Apollo Client 3.3, readFragment threw MissingFieldError exceptions to report missing fields, and returned null only when reading a fragment from a nonexistent ID. Beginning with Apollo Client 3.3, readFragment always returns null to indicate insufficient data (missing ID or missing fields), instead of throwing a MissingFieldError.

writeFragment

In addition to reading "random-access" data from the Apollo Client cache with readFragment, you can write data to the cache with the writeFragment method.

Any changes you make to cached data with writeFragment are not pushed to your GraphQL server. If you reload your environment, these changes will disappear.

The writeFragment method resembles readFragment, except it requires an additional data variable. For example, the following call to writeFragment updates the completed flag for a Todo object with an id of 5:

All subscribers to the Apollo Client cache (including all active queries) see this change and update your application's UI accordingly.

watchFragment Requires ≥ 3.10.0 useFragment Requires ≥ 3.8.0

You can read data for a given fragment directly from the cache using the useFragment hook. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. See the API reference.

Combining reads and writes

You can combine readQuery and writeQuery (or readFragment and writeFragment) to fetch currently cached data and make selective modifications to it. The following example creates a new Todo item and adds it to your cached to-do list. Remember, this addition is not sent to your remote server.

Using updateQuery and updateFragment Requires ≥ 3.5

As a convenience, you can use cache.updateQuery or cache.updateFragment to combine reading and writing cached data with a single method call:

Each of these methods takes two parameters:

After either method fetches data from the cache, it calls its update function and passes it the cached data. The update function can then return a value to replace that data in the cache. In the example above, every cached Todo object has its completed field set to true (and other fields remain unchanged).

Please note that the replacement value has to be calculated in an immutable way. You can read more about immutable updates in the React documentation .

If the update function shouldn't make any changes to the cached data, it can return undefined.

The update function's return value is passed to either writeQuery or writeFragment, which modifies the cached data.

See the full API reference for cache.updateQuery and cache.updateFragment.

Using cache.modify

The modify method of InMemoryCache enables you to directly modify the values of individual cached fields, or even delete fields entirely.

Parameters

Canonically documented in the API reference, the modify method takes the following parameters:

A modifier function applies to a single field. It takes its associated field's current cached value as a parameter and returns whatever value should replace it.

Here's an example call to modify that modifies a name field to convert its value to upper case:

If you don't provide a modifier function for a particular field, that field's cached value remains unchanged.

Values vs. references

When you define a modifier function for a field that contains a scalar, an enum, or a list of these base types, the modifier function is passed the exact existing value for the field. For example, if you define a modifier function for an object's quantity field that has current value 5, your modifier function is passed the value 5.

However, when you define a modifier function for a field that contains an object type or a list of objects, those objects are represented as references. Each reference points to its corresponding object in the cache by its cache ID. If you return a different reference in your modifier function, you change which other cached object is contained in this field. You don't modify the original cached object's data. Additionally, modifying a field (or adding a new one) in a reference will only take effect for the location you're modifying.

Modifier function utilities

A modifier function can optionally take a second parameter, which is an object that contains several helpful utilities.

Some of these utilities (namely, the readField function and the DELETE sentinel object) are used in the examples below. For descriptions of all available utilities, see the API reference.

Examples Example: Removing an item from a list

Let's say we have a blog application where each Post has an array of Comments. Here's how we might remove a specific Comment from a paginated Post.comments array:

Let's break this down:

Example: Adding an item to a list

Now let's look at adding a Comment to a Post:

When the comments field modifier function is called, it first calls writeFragment to store our newComment data in the cache. The writeFragment function returns a reference (newCommentRef) that points to the newly cached comment.

As a safety check, we then scan the array of existing comment references (existingCommentRefs) to make sure that our new isn't already in the list. If it isn't, we add the new comment reference to the list of references, returning the full list to be stored in the cache.

Example: Updating the cache after a mutation

If you call writeFragment with an options.data object that the cache is able to identify ( based on its __typename and cache ID fields), you can avoid passing options.id to writeFragment.

Whether you provide options.id explicitly or let writeFragment figure it out using options.data, writeFragment returns a Reference to the identified object.

This behavior makes writeFragment a good tool for obtaining a Reference to an existing object in the cache, which can come in handy when writing an update function for useMutation:

For example:

In this example, useMutation automatically creates a Comment and adds it to the cache, but it doesn't automatically know how to add that Comment to the corresponding Post's list of comments. This means that any queries watching the Post's list of comments won't update.

To address this, we use the update callback of useMutation to call cache.modify. Like the previous example, we add the new comment to the list. Unlike the previous example, the comment was already added to the cache by useMutation. Consequently, cache.writeFragment returns a reference to the existing object.

Example: Deleting a field from a cached object

A modifier function's optional second parameter is an object that includes several helpful utilities, such as the canRead and isReference functions. It also includes a sentinel object called DELETE.

To delete a field from a particular cached object, return the DELETE sentinel object from the field's modifier function, like so:

Example: Invalidating fields within a cached object

Normally, changing or deleting a field's value also invalidates the field, causing watched queries to be reread if they previously consumed the field.

Using cache.modify, it's also possible to invalidate the field without changing or deleting its value, by returning the INVALIDATE sentinel:

If you need to invalidate all fields within a given object, you can pass a modifier function as the value of the fields option:

When using this form of cache.modify, you can determine individual field names using details.fieldName. This technique works for any modifier function, not just those that return INVALIDATE.

Obtaining an object's cache ID

If a type in your cache uses a custom cache ID (or even if it doesn't), you can use the cache.identify method to obtain the cache ID for an object of that type. This method takes an object and computes its ID based on both its __typename and its identifier field(s). This means you don't have to keep track of which fields make up each type's cache ID.

Example

Let's say we have a JavaScript representation of a cached GraphQL object, like this:

If we want to interact with this object in our cache with methods like writeFragment or cache.modify, we need the object's cache ID. Our Book type's cache ID appears to be custom, because the id field isn't present.

Instead of needing to look up that our Book type uses the isbn field for its cache ID, we can use the cache.identify method, like so:

The cache knows that the Book type uses the isbn field for its cache ID, so cache.identify can correctly populate the id field above.

This example is straightforward because our cache ID uses a single field (isbn). But custom cache IDs can consist of multiple fields (such as both isbn and title). This makes it much more challenging and repetitive to specify an object's cache ID without using cache.identify.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4