Persistence

ActiveJS Units can be made persistent by setting a configuration flag to true. By default, persistent Units use localStorage for the persistence. You can change it to any storage API that implements Storage interface. e.g.: sessionStorage

Creating a persistent Unit

All that it takes to make a Unit persistent is a flag, and a unique id. The id is required to identify the Unit and its stored value.

// this will throw an error, id is required
const preferencesUnit = new DictUnit({persistent: true});

// this will work
const preferencesUnit = new DictUnit({id: 'preferences', persistent: true});


// update Unit's value
preferencesUnit.set('side', 'dark');
// value in the LocalStorage would become {"side": "dark"}

// refresh the browser window

// check value
console.log(preferencesUnit.value()) // logs {"side": "dark"}

Voila! we're done. No manual saving, no manual retrieving.

Initial value vs persisted value

When you provide an initial value to a persistent Unit, at first instance it gets saved to the persistent storage immediately, but when you refresh the browser window or open a new one, on the second instance the stored value takes precedence over the provided initial value.

Clearing the persisted value

Persisted value can be cleared in two ways, per Unit, or every Unit in a Storage instance.

  • To clear the persisted value of a Unit, you can use Unit.clearPersistedValue()

  • To clear all Units' persisted values from the default storage, you can use the global function clearPersistentStorage().

  • If you want to clear a particular storage you can pass it to the clearPersistentStorage() function. e.g. clearPersistentStorage(window.sessionStorage)

Changing the persistence storage

All Units use the localStorage for persistence by default, but it can be changed to sessionStorage as well, and you can either change it globally or for a specific Unit.

Changing storage for one Unit

Changing default storage for every Unit

You can change the default Storage API used by ActiveJS Units through the global Configuration.

Supported data types

It's advised to put only serializable data types in a persistent Unit, otherwise, the information will be lost in serialization done to save it in the LocalStorage. Non-serializable data types like Date, Map, Set, etc. are not supported.

All the data types that support JSON.stringify and JSON.parse can be used as values.

Note: Date object works with JSON.stringify, however it can't be parsed back to a Date object. When using the persisted value of the Unit, you'll only get a string representation of Date, not a Date object.

Last updated

Was this helpful?