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(
  initialTables?: Tables,
  initialValues?: Values,
): Promise<Persister>
TypeDescription
initialTables?Tables

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

initialValues?Values

An optional Values object used when the underlying storage has not previously been populated, since v3.0.0.

returnsPromise<Persister>

A Promise containing a reference to the Persister object.

The optional parameter allows you to specify what the initial Tables object for the Store will be if there is nothing at first persisted. Using this instead of the initialTables parameter in the regular createStore function allows you to easily 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).

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();