Persisting widget state
In this tutorial, we'll explore how to persist the state of a widget, allowing it to be restored later, such as when the page is reloaded.
Saving state
Each widget has a addStateListener
method into which you can pass a callback function to receive all
changes to the widget’s state and a getState
method by which you can get current state of the widget
function handleWidgetStateChange(state) {
saveWidgetState(state)
}
widget.addStateListener(handleWidgetStateChange)
// or
saveWidgetState(widget.getState())
The internal implementation of the saveWidgetState
function in your code is up to you.
You can use a database, local storage, etc. For demo purposes, we will use a local storage:
const LOCAL_STORAGE_KEY = 'SOME_KEY'
function saveWidgetState(state) {
window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(state))
}
function getWidgetState() {
return JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY))
}
Using saved state
To apply the saved state to a widget, you need to pass it to the first render after initializing the widget through the constructor.
const initialState = getWidgetState()
const widget = newWatchListWidget({
element: domElement,
providers: dataProviders,
state: initialState,
})