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.
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.
Be advised that you should only change it once and that too before initializing any persistent Unit.
Otherwise, some persistent Units will save their values in LocalStorage
and try to restore it from SessionStorage
. Also, the global functionclearPersistentStorage()
won't be able to clear persisted values from the other storage, you'll have to manually provide the non-current storage you want to clean up.
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