TL;DR: How to access data/state in the callback definitions (e.g. Input(...)
or State(...)
) ?
Consider the following dummy example:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Output, Input, State
df = pd.DataFrame(
{
"user": ["a", "b", "c", "d"],
"data": [1, 5, 6, 3],
"category": ["x", "x", "y", "y"],
}
)
app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
app.layout = html.Div(
[
dcc.Store("users"),
dcc.Dropdown(
id="dropdown",
options=[{"label": cat, "value": cat} for cat in ["x", "y"]],
value="x",
),
html.Div(id="buttons-container"),
html.Div(id="output-text"),
]
)
@app.callback(Output("users", "data"), [Input("dropdown", "value")])
def get_users(cat):
if cat:
return df.query("category == @cat")["user"].to_list()
else:
return None
@app.callback(Output("buttons-container", "children"), [Input("users", "data")])
def create_buttons(users):
if users:
return [html.Button(f"btn-{user}", id=f"btn-{user}") for user in users]
else:
return None
@app.callback(
Output("output-text", "children"),
[Input(f"btn-{user}", "n_clicks") for user in **NEED USERS.DATA HERE**],
)
def update_output(*args):
user = dash.callback_context.triggered[0]["prop_id"].split(".")[0].split("-")[-1]
return f"You clicked user {user} button"
if __name__ == "__main__":
app.run_server(debug=True)
In this app,
- a dataframe
df
contains one row for eachuser
with an associated categoryx
ory
- the
get_users
callback store the list ofusers
that belong to the category selected in the dropdown - from this list of
users
, thecreate_buttons
callback create one button for each user - in the
update_output
, I want to connect each visible buttons to an output text. However, I need to access data during the callback definitions (Input(...)
) to know the id of the buttons.
I have read the proposed solutions in Dynamic Controls and Dynamic Output Components. But in real life, my application is connected with a Google Sheet. So I don’t know in advance the users and categories.
I tried several things without success. Do you have a solution or ideas to avoid this problem?