Relay Cache With Flux Pattern?

- 1 answer

I'd really like to incorporate the Relay cache within my Flux store so I can do "time-travel" and gain deep insight into the application.

It looks like the Relay store and actions are all classes which aren't serializable which is bummer. But it looks like I ought to be able to separate the cache from the network requests and save the cache in a Flux store.

Does that sound interesting or am I barking up the wrong tree?



Relay can certainly be used alongside Flux, and we've spoken to many developers who are using them together successfully. The general pattern is to let Relay own the cache of server data and manage communication with the server, and use Flux for storing & updating client-only data.

Reading Relay Data From Flux

If the Flux stores need access to server data, they can use the Relay.Store APIs to fetch data from the server and read it from the cache:

// build a query 
var query = Relay.createQuery(Relay.QL`query { ... }`, {var: 'value'});
// fetch any missing data for this query
Relay.Store.primeCache({query}, readyState => {
  if (readyState.done) {
    // read data once the cache is populated
    var data = Relay.Store.readQuery(query)[0];

Inspecting the Relay Cache

Relay doesn't directly support time-travel debugging. However, we are actively working on developer tools for Relay and the initial version of this should be available soon. In the meantime there are a few options for inspecting the state of the cache:

  • Intercept and record all low-level updates to the Relay store. This can be done by injecting a cache manager with RelayStoreData.getDefaultInstance().injectCacheManager(...) (note that the API names may change, but the cache manager API itself is stable). The CacheManager interface is defined here - note that this will allow you to record all the values written to Relay's cache to build up any visualization you'd like of the data. All of the field values written to the cache manager are JSON-serializable. Note that the cache manager cannot write data back into the store, so this would primarily allow you to have visibility into the current state of the cache.
  • Intercept all query and mutation requests at the network layer by injecting a custom network layer. This will give an indication of what data your application is requesting and what it's receiving back from the server.