I've got react native application with GraphQL API where is usage react-relay library. And I need to implement disk cache to the application, I see that request are caching already in runtime, but after reload application the request again reload data from server but need getting from cache.
Asked
Active
Viewed 290 times
1
-
+1 here. I can't find anything related to persisting react relay cache to disk anywhere (neither react relay docs, nor google). Anyone? – plamenh Nov 19 '21 at 10:40
1 Answers
0
Ok, here's a bit crude solution I had to come up myself with:
import {
Environment,
Network,
QueryResponseCache,
RecordSource,
Store,
} from 'relay-runtime';
const oneMinute = 60 * 1000;
const cacheTtl = oneMinute * 1440; // 24 hours
const cache = new QueryResponseCache({ size: 500, ttl: cacheTtl });
// Restore cache from localStorage
const localStorageCacheResponses = localStorage.getItem('relay-cache');
if (localStorageCacheResponses) {
cache._responses = new Map(Object.entries(JSON.parse(localStorageCacheResponses)));
console.log('cache restored');
}
Then, when updating the cache:
// Update cache on queries
if (isQuery && json) {
cache.set(queryID, variables, json);
}
// Clear cache on mutations
if (isMutation) {
console.log('cache cleared');
cache.clear();
}
// Update localStorage cache copy (for persistent cache storage between sessions)
localStorage.setItem('relay-cache', JSON.stringify(Object.fromEntries(cache._responses)));
Feel free to use whatever persistent storage solution you like. I am using localStorage, because webapp. Of course, this is completely unsecure, so it is a big no for sensitive information. Also, You might need to think about clearing the cache at some point (login, logout, etc.), so that if you have different users, data does not get mixed up.

plamenh
- 131
- 8