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(initialContent?: Content): Promise<Persister<Persist>>
TypeDescription
initialContent?Content

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

returnsPromise<Persister<Persist>>

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 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.

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

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.

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

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

Since

v1.0.0