Skip to main content

Core Cache Persistence

gqless offers easy to use Cache persistence.

  • client.backupPersistence gets all the cache and returns a string, and optionally accepts a version string parameter, that allows for invalidating previous versions of cache, and ignoring them.
  • client.restorePersistence accepts a possible string that should have been stored persistently in some way, and optionally accepts a second version string paramater, that should be the same as the one used in backupPersistence.

Data Revalidation#

For an effective usage of Cache persistence it's almost always required some kind of automatic data refetching, and for that reason we recommend you to use:

Examples#

In both examples we use a debounce function exported from gqless that reduces the amount calls to the storages, improving the user experience.

Here you can read a quick explanation of debouncing

localStorage#

In this example, for simplicity we are using localStorage to offer cache persistence, but for most serious applications we recommend using async solutions like localForage.

//...
import { debounce } from 'gqless';
// ...
export const client = createClient<
GeneratedSchema,
SchemaObjectTypesNames,
SchemaObjectTypes
>({
schema: generatedSchema,
scalarsEnumsHash,
queryFetcher,
// ...
});
// ...
// This conditional should not be present for client-side only apps
if (typeof window !== 'undefined') {
const backup = debounce(() => {
localStorage.setItem('gqless-cache', client.backupPersistence('v1'));
}, 1000);
client.restorePersistence(localStorage.getItem('gqless-cache'), 'v1');
client.eventHandler.onFetchSubscribe((promise) => promise.then(backup));
client.eventHandler.onCacheChangeSubscribe(backup);
}

Async Storages#

We recommend using localForage or @react-native-async-storage/async-storage

import { debounce } from 'gqless';
// ...
import localForage from 'localforage';
// import AsyncStorage from '@react-native-async-storage/async-storage';
export const client = createClient<
GeneratedSchema,
SchemaObjectTypesNames,
SchemaObjectTypes
>({
schema: generatedSchema,
scalarsEnumsHash,
queryFetcher,
// ...
});
// ...
export const clientReadyPromise = client.restorePersistence(() => {
// return AsyncStorage.getItem('gqless-cache');
return localForage.getItem('gqless-cache');
}, 'v1');
// This conditional should not be present for React Native or client-side only apps
if (typeof window !== 'undefined') {
const backup = debounce(() => {
// AsyncStorage.setItem('gqless-cache', client.backupPersistence('v1'));
localForage.setItem('gqless-cache', client.backupPersistence('v1'));
}, 1000);
client.eventHandler.onFetchSubscribe((promise) => promise.then(backup));
client.eventHandler.onCacheChangeSubscribe(backup);
}

Last updated on by github-actions[bot]