how do you store variables in dash core components

Question:

I am trying to store a variable into memory using dash_core_components.Store, but it doesn’t seem to be saving the incremented number to memory. what I want to happen is everytime I press the button, the number stored in memory increases by 10 – instead the variable doesn’t seem to be saving and just outputs 15.

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

x = 5

app.layout = html.Div([
    dcc.Store(id='memory-data', data = {'the-data': x}),
    html.Div([
        html.Button('click me', id='add-button')
    ]),
    html.Div(id='debug-out'),
])

@app.callback(dash.dependencies.Output('debug-out', 'children'),
             [dash.dependencies.Input('add-button', 'n_clicks')],
             [dash.dependencies.State('memory-data', 'data')])
def button_pressed(clicks, data):
    
    data['the-data'] += 10
    return data['the-data']
Asked By: ChrisM

||

Answers:

You aren’t outputting to the dcc.Store component, so it never changes. That’s why it keeps returning 15. What you would have to do is set up two callbacks, like in this example from the docs. One updates the data in the store, and the other retrieves the updated data.

Answered By: coralvanda

Fwiw this example from the docs … https://dash.plotly.com/dash-core-components/store... does not actually work.

Try click on the buttons for yourself.

Instead of referring the OP to non working docs, it might be helpful to provide a working example of how to use dcc.Store.

Answered By: user3445213
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.