How to persist (dump) data to local storage and load it at later sessions?

时间:2016-07-11 21:41:21

标签: relayjs

I want to persist some parts of data from Relay store and load it again at later sessions for better user experience. (I am using Relay with react native for context).

The data can be relatively large (up to few thousands of records) and doesn't need to be 100% in sync with the server. I want to persist the records across sessions as I don't want to refetch the data every time user opens an app. It will be both burden to the server and bad user experience (loading time).

1 个答案:

答案 0 :(得分:0)

您可以在设置 Relay 时创建的环境文件中访问 Relay 的完整存储。如果您尝试控制台注销 recordSource,您应该会看到您的整个存储,并且每次 Relay 处理新操作(查询/变异/订阅)时它都应该更新,所以也许您所要做的就是将其存储在持久化的存储(即 localStorage)。

示例:

// your-app-name/src/RelayEnvironment.js
import {Environment, Network, RecordSource, Store} from 'relay-runtime';
import fetchGraphQL from './fetchGraphQL';

async function fetchRelay(params, variables) {
  console.log(`fetching query ${params.name} with ${JSON.stringify(variables)}`);
  return fetchGraphQL(params.text, variables);
}

const recordSource = new RecordSource();
console.log(recordSource);
// Store `recordSource` in persisted storage (i.e. localStorage) here.
if(typeof window !== "undefined") { // optional if you're not doing SSR
  window.localStorage.setItem("relayStore", JSON.stringify(recordSource));
}

export default new Environment({
  network: Network.create(fetchRelay),
  store: new Store(recordSource),
});