6

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 Answer 1

1

You have access to Relay's full store in the environment file you create when setting up Relay. If you try console logging out recordSource you should see your entire store, and it should update every time Relay processes a new operation (Query/Mutation/Subscription), so maybe all you have to do is store that in your persisted storage (i.e. localStorage).

Example:

// 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),
});
3
  • Well, this will always persist an empty ._records object, as it is done before any operations populate the recordSource. Also, at what point do you restore the data, given that we solve the first problem?
    – plamenh
    Nov 19, 2021 at 16:52
  • I suggest window.localStorage.setItem("relayStoreRecords", JSON.stringify(Object.fromEntries(recordSource._records))); in fetchRelay and recordSource._records = new Map(Object.entries(JSON.parse(localStorageRelayStoreRecords))); somewhere outside.
    – plamenh
    Nov 19, 2021 at 17:05
  • And just a bit of advice here - localStorage seems to be kind of inadequate in terms of capacity. It only holds 5 mb of capacity and breaks everything when you hit the cap.
    – plamenh
    Nov 22, 2021 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.