TinyBase logoTinyBase β

createLocalPersister

Essential

The createLocalPersister function creates a LocalPersister object that can persist the Store to the browser's local storage.

createLocalPersister(
  store: Store | MergeableStore,
  storageName: string,
  onIgnoredError?: (error: any) => void,
): LocalPersister
TypeDescription
storeStore | MergeableStore

The Store or MergeableStore to persist.

storageNamestring

The unique key to identify the storage location.

onIgnoredError?(error: any) => void

An optional handler for the errors that the Persister would otherwise ignore when trying to save or load data. This is suitable for debugging persistence issues in a development environment, since v4.0.4.

returnsLocalPersister

A reference to the new LocalPersister object.

A LocalPersister supports both regular Store and MergeableStore objects.

As well as providing a reference to the Store to persist, you must provide a storageName parameter which is unique to your application. This is the key that the browser uses to identify the storage location.

Since v10.2, if another tab deletes what it saved while it is automatically loading, or clears the local storage, the Store starts again from nothing, or from the initial content given to the startAutoLoad method. It no longer keeps what was deleted, for its next save to bring back: a MergeableStore, which merges what another tab saves, would otherwise undo a reset made in another tab.

Example

This example creates a LocalPersister object and persists the Store to the browser's local storage.

import {createStore} from 'tinybase';
import {createLocalPersister} from 'tinybase/persisters/persister-browser';

const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
const persister = createLocalPersister(store, 'pets');

await persister.save();
console.log(localStorage.getItem('pets'));
// -> '[{"pets":{"fido":{"species":"dog"}}},{}]'

await persister.destroy();
localStorage.clear();

Since

v1.0.0