NerdWalletOSS / apollo-cache-policies

An extension of the Apollo 3 cache with support for advanced cache policies.
Apache License 2.0
156 stars 22 forks source link

Cached Reactive Vars #49

Closed danReynolds closed 2 years ago

danReynolds commented 2 years ago

Apollo Client introduced Reactive vars as a useful way to quickly and easily maintain reactive state across applications.

They were designed, however, to existing outside of the cache. This can be challenging when working with applications using persistent caches like Apollo Cache Persist, since it means that persistent state needs to be stored in the cache and therefore cannot use reactive variables.

Because of how easy Reactive variables are to work with, it would be helpful to have them stored and hydrated from the cache similarly to other local data read and written with the readFragment, readQuery, writeFragment and writeQuery APIs.

This proposal introduces a makeCachedVar API that works the same as a reactive variable, but additionally automatically writes changes to the variable to the cache and hydrates cached reactive variables with the cached value when using tools like Apollo Cache Persist.

The cached reactive var API should look very similar to the existing makeVar API:

import { makeVar } from "@apollo/client";
import { makeCachedVar } from "@nerdwallet/apollo-cache-policies";

const rv = makeVar<boolean>(true);
const cachedRv = makeCachedVar<boolean>('id', true);

Note the introduction of a string ID parameter used as the a unique identifier of the cached variable. The usage is then the same as any other reactive variable.

Looking for API feedback and questions/concerns about the usefulness and implementation details of this proposal.

benhan23 commented 2 years ago

Note the introduction of a string ID parameter used as the a unique identifier of the cached variable.

Is there a way we can ensure that this unique identifier is truly unique?

danReynolds commented 2 years ago

Note the introduction of a string ID parameter used as the a unique identifier of the cached variable.

Is there a way we can ensure that this unique identifier is truly unique?

It could error if you do it multiple times with the same key I suppose, what happens currently if you use the same ID for multiple would be that they're both storing to the same cache entry so then on hydration, the one that had been updated last and persisted that to the cache would be the value they're both hydrated with.

There's nothing to stop you from writing the same ID to the cache for any other type of cache entity, not just reactive vars

danReynolds commented 2 years ago

Thanks for taking this on, @danReynolds! The API makes sense to me, with the possible exception of reset() (see comment thread).

Would it make sense to update the library API docs in this PR?

Yea was planning to add docs once the API was nailed down and we confirmed we wanted to move forward with this.