I am messing about with the dcc.Store (https://dash.plot.ly/dash-core-components/store)
There is a clear_data attribute but I cannot figure out how to get it to work. I want to add an html button to clear the local store.
All I am doing is incrementing a variable, storing it and reading it back ... the example given by Dash does not give any indication how to clear the values
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input, State
from dash.exceptions import PreventUpdate
app = dash.Dash(__name__)
app.config['suppress_callback_exceptions']=True
app.layout = html.Div([
dcc.Store(id='buttonstore3', storage_type='local'),
html.Div([
html.Button('Local', id='my-button3')
]),
html.Div([
html.Button('Clear Local', id='my-button4')
]),
html.Div([
html.Table([
html.Thead([
html.Tr([
html.Th('Local clicks')
])
]),
html.Tbody([
html.Tr([
html.Td(0, id='local-clicks'),
])
])
])
])
])
####### Add to Local Store
@app.callback(Output('buttonstore3', 'data'),
[Input('my-button3', 'n_clicks')],
[State('buttonstore3', 'data')])
def on_click(n_clicks, data):
if n_clicks is None:
raise PreventUpdate
data = data or 0
data = data + 1
return data
@app.callback(Output('local-clicks', 'children'),
[Input('buttonstore3', 'modified_timestamp')],
[State('buttonstore3', 'data')])
def on_data(ts, data):
if ts is None:
raise PreventUpdate
data = data or 0
return data
if __name__ == '__main__':
app.run_server(debug=True, threaded=True)
It says in the docs here:
clear_data - Set to True to remove the data contained in data_key.
So you could add the following callback to your app:
@app.callback(Output('buttonstore3', 'clear_data'),
[Input('my-button4', 'n_clicks')])
def clear_click(n_click_clear):
if n_click_clear is not None and n_click_clear > 0:
return True
return False
You could also update your on_click callback to take in inputs from both buttons, and output to the data prop based on which button was clicked, like this:
####### Add to Local Store
@app.callback(Output('buttonstore3', 'data'),
[Input('my-button3', 'n_clicks'),
Input('my-button4', 'n_clicks')],
[State('buttonstore3', 'data')])
def on_click(n_clicks_add, n_clicks_clear, data):
if n_clicks_add is None:
n_clicks_add = 0
if n_clicks_clear is None:
n_clicks_clear = 0
if data is None:
data = 0
trigger = dash.callback_context.triggered[0]
if trigger['prop_id'] == 'my-button3.n_clicks':
data += 1
elif trigger['prop_id'] == 'my-button4.n_clicks':
data = 0
else:
raise ValueError('Unrecognized trigger: {}'.format(trigger['prop_id']))
return data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With