Im quite new to web development in python and am developing a dash-plotly application at the moment. In the application there is a dropdown menu for the user to select a specific time interval for shown data in the graph. When the page is refreshed the selection returns obviously back to default. This simplified code shows the dropdown setup:
import dash_core_components as dcc
app = dash.Dash(__name__)
app.layout = html.Div(
dcc.Store('memory-intervals', storage_type='session')
dcc.Dropdown(
id='time',
options=get_intervals(),
value=Interval.DAY.value,
multi=False,
),
)
What I understood for now is, that I can store data in the browser session through dash's Store component. I managed to store selection like this:
@app.callback(
Output('memory-intervals', 'data'),
Input('time', 'value'),
)
def select_interval(interval):
if interval is None:
raise PreventUpdate
return interval
So I am stuck at this point... how can set the store's data as selection value after page reload?
Thank you in advance!
You could use the Dash persistence feature.
As per documentation:
persistence_type ('local', 'session', or 'memory'; default 'local'): Where persisted user changes will be stored:
memory: only kept in memory, reset on page refresh. This is useful for example if you have a tabbed app, that deletes the component when a different tab is active, and you want changes persisted as you switch tabs but not after reloading the app.
local: uses window.localStorage. This is the default, and keeps the data indefinitely within that browser on that computer.
session: uses window.sessionStorage. Like 'local' the data is kept when you reload the page, but cleared when you close the browser or open the app in a new browser tab.
In your example, if you need to preserve a dropdown value only after reloading, but not after exiting the browser or closing the tab, you could write:
import dash_core_components as dcc
app = dash.Dash(__name__)
app.layout = html.Div(
dcc.Store('memory-intervals', storage_type='session')
dcc.Dropdown(
id='time',
options=get_intervals(),
value=Interval.DAY.value,
multi=False,
persistence = True,
persistence_type = 'session'
),
)
However, if you need to keep the selection indefinitely within that browser on that computer you could simply use persistence = True because the 'local' type is the default.