react-relay-network-modern icon indicating copy to clipboard operation
react-relay-network-modern copied to clipboard

hook to invalidate cache items.

Open graingert opened this issue 7 years ago • 8 comments

graingert avatar Jan 16 '18 22:01 graingert

For now It can be done in such way:

let _globalCacheRef;

const RRNL =  new RelayNetworkLayer([
        cacheMiddleware({
          size: 100,
          ttl: 900000,
          onInit: cache => (_globalCacheRef = cache),
        })
]);

if (_globalCacheRef) {
  _globalCacheRef.clear();
}

If you have any ideas how to improve this, let me know.

nodkz avatar Jan 17 '18 04:01 nodkz

Hmm I'd like to be able to clear individual items

graingert avatar Jan 17 '18 08:01 graingert

The cache class is used from Relay. This one https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayQueryResponseCache.js

Copy method from there

function getCacheKey(queryID: string, variables: Variables): string {
  return JSON.stringify(stableCopy({queryID, variables}));
}

And then remove cached data in such way:

_globalCacheRef._responses.delete(getCacheKey(queryID, variables));

Cache keep server responses for your query by query name and its variables. So when the same query with variables requested, it takes response from cache.

nodkz avatar Jan 17 '18 09:01 nodkz

Can we get a public API to do this?

graingert avatar Jan 17 '18 09:01 graingert

BTW you may open PR to relay repo for improving its cache - add delete method. And I think, it has big chances to be included in 1.5.0

nodkz avatar Jan 17 '18 09:01 nodkz

Sure, as a workaround you may add this code to my repo.

nodkz avatar Jan 17 '18 09:01 nodkz

Put here something like:

cache.delete = (queryID, variables) => {
  cache._responses.delete(getCacheKey(queryID, variables));
}

and getCacheKey function put outside (before) queryMiddleware function in same file.

nodkz avatar Jan 17 '18 09:01 nodkz

https://github.com/facebook/relay/issues/1687#issuecomment-302965908 suggests that the cache should be cleared on each mutation. It would be nice to have the ability to do something more granular, but that seems like it should be the default?

jscheid avatar Feb 21 '18 23:02 jscheid