简体   繁体   中英

React relay disk cache

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM