TinyBase logoTinyBase

load

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

load(
  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 is asynchronous because the persisted data may be on a remote machine or a filesystem. 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.

Examples

This example creates an empty Store, and loads data into it from the browser's session storage, which for the purposes of this example has been previously populated.

sessionStorage.setItem('pets', '[{"pets":{"fido":{"species":"dog"}}},{}]');

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

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

sessionStorage.clear();

This example creates an empty Store, and loads data into it from the browser's session storage, which is at first empty, so the optional parameter is used. The second time the load method is called, data has previously been persisted and instead, that is loaded.

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

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

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

sessionStorage.clear();