load
The load
method gets persisted data from storage, and loads it into the Store
with which the Persister
is associated, once.
load(initialTables?: Tables): Promise<Persister>
Type | Description | |
---|---|---|
initialTables? | Tables | An optional |
returns | Promise<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 currently 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 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();