Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 690
Joon Avatar asked Jul 11 '16 21:07

Joon


People also ask

Does local storage persist across sessions?

The localStorage read-only property of the window interface allows you to access a Storage object for the Document 's origin; the stored data is saved across browser sessions.

How do I keep local storage after refresh?

To store the form data in JavaScript localStorage, we'll use the setItem() method. It stores the data in the localStorage object and takes the key and value parameters as input. The parameters can be later used to retrieve the data when the browser reloads the page or a new session is initiated.

What is persistent local storage?

localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.


1 Answers

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),
});
like image 72
Richard Guerre Avatar answered Sep 30 '22 00:09

Richard Guerre