TinyBase logoTinyBase

startAutoLoad

The startAutoLoad method gets persisted data from storage, and loads it into the Store with which the Persister is associated, once, and then continuously.

startAutoLoad(initialContent?: Content): Promise<LocalPersister>
TypeDescription
initialContent?Content

An optional Content object used when the underlying storage has not previously been populated.

returnsPromise<LocalPersister>

A Promise containing a reference to the Persister object.

The optional parameter allows you to specify what the initial content for the Store will be if there is nothing currently persisted or if the load fails (for example when the Persister is remote and the environment is offline). This allows you to fallback or instantiate a Store whether it's loading from previously persisted storage or being run for the first time.

This method first runs a single call to the load method to ensure the data is in sync with the persisted storage. It then continues to watch for changes to the underlying data (either through events or polling, depending on the storage type), automatically loading the data into the Store.

This method is asynchronous because it starts by making a single call to the asynchronous load method. Even for those storage types that are synchronous (like browser storage) it is still recommended that you await calls to this method or handle the return type natively as a Promise.

Example

This example creates an empty Store, and loads data into it from the browser's session storage, which at first is empty (so the initialTables parameter is used). Subsequent changes to the underlying storage are then reflected in the Store (in this case through detection of StorageEvents from session storage changes made in another browser tab).

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

const store = createStore();
const persister = createSessionPersister(store, 'pets');

await persister.startAutoLoad([{pets: {fido: {species: 'dog'}}}, {}]);
console.log(store.getTables());
// -> {pets: {fido: {species: 'dog'}}}

// In another browser tab:
sessionStorage.setItem('pets', '[{"pets":{"toto":{"species":"dog"}}},{}]');
// -> StorageEvent('storage', {storageArea: sessionStorage, key: 'pets'})

// ...
console.log(store.getTables());
// -> {pets: {toto: {species: 'dog'}}}

persister.destroy();
sessionStorage.clear();

Since

v1.0.0