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).
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.
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.
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.
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),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With