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

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

initialValues?any

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

returnsPromise<Persister>

A Promise containing a reference to the Persister object.

The optional parameters allow 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).

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