TinyBase logoTinyBase beta

createCustomPersister

The createCustomPersister function creates a Persister object that you can configure to persist the Store in any way you wish.

createCustomPersister(
  store: Store,
  getPersisted: () => Promise<undefined | null | string>,
  setPersisted: (json: string) => Promise<void>,
  startListeningToPersisted: (didChange: Callback) => void,
  stopListeningToPersisted: Callback,
): Persister
TypeDescription
storeStore

The Store to persist.

getPersisted() => Promise<undefined | null | string>

An asynchronous function which will fetch JSON from the persistence layer (or null or undefined if not present).

setPersisted(json: string) => Promise<void>

An asynchronous function which will send JSON to the persistence layer.

startListeningToPersisted(didChange: Callback) => void

A function that will register a didChange listener on underlying changes to the persistence layer.

stopListeningToPersistedCallback

A function that will unregister the listener from the underlying changes to the persistence layer.

returnsPersister

A reference to the new Persister object.

As well as providing a reference to the Store to persist, you must provide functions that handle how to fetch, write, and listen to, the persistence layer.

The other creation functions (such as the createSessionPersister function and createFilePersister function, for example) all use this function under the covers. See those implementations for ideas on how to implement your own Persister types.

Example

This example creates a custom Persister object and persists the Store to a local string called storeJson and which would automatically load by polling for changes every second.

const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
let storeJson;
let interval;

const persister = createCustomPersister(
  store,
  async () => storeJson,
  async (json) => (storeJson = json),
  (didChange) => (interval = setInterval(didChange, 1000)),
  () => clearInterval(interval),
);

await persister.save();
console.log(storeJson);
// -> '{"pets":{"fido":{"species":"dog"}}}'

storeJson = '{"pets":{"fido":{"species":"dog","color":"brown"}}}';
await persister.load();

console.log(store.getTables());
// -> {pets: {fido: {species: 'dog', color: 'brown'}}}

persister.destroy();