Hi, I’m sort of new to Dash so please excuse me if this question doesn’t quite make sense:
I’m currently making a dashboard to visualize data. I have all the dashboard configurations and source data stored in global variables that are initialized when app.py runs. All this works great; however, I’m trying to implement the ability for users to upload a new configuration file that updates the entire dashboard (including the source data).
Currently, it seems to work as intended if I update all the global variables in a callback for the file upload and refresh the page. However, I understand global variables are unideal. As such, I’m attempting to do the same with dcc.Store, but I’m struggling on certain aspects of this.
For example, I have non-callback, regular functions, such as for initializing dropdown options in the layout or plotting graphs. These functions currently rely on the global variables. If I no longer use global variables and instead store them in dcc.Store’s data property, how can I access them, given that they’re outside of callbacks?
Any ideas would be really appreciated. If there’s a better way of doing this please let me know also!
Hi,
You can’t access them outside the callback, but you can write a callback that updates a page container and use functions (or just write some logic) to create its children. Dummy example:
app.layout = html.Div(
[
dcc.Upload(...),
dcc.Store(id="store", data=dict(dropdown=["a", "b"]),
html.Div(id="container"),
]
)
@callback(
Output("container", "children"),
Input("store", "data")
)
def update_page(data):
children = []
if "dropdown" in data:
dd_options = data["dropdown"]
dd = dcc.Dropdown(dd_options, dd_options[0], id="dropdown")
children.append()
return children
You can of course create one “container” component to be updated by values in the Store or change individual props instead of recreating them, i.e. to do the followign in the example above:
@callback(
Output("dropdown", "options"),
Input("store", "data")
)
def update_page(data):
children = []
if "dropdown" in data:
return data["dropdown"]
The right approach depends a lot on what the other callbacks do, as you must make sure that you won’t have missing Input/Output when they are triggered (see here). Besides, app.validation_layout
can be helpful for you.
Lastly, in some simple cases, you can benefit from writing the components as dictionaries as in this old thread.
Hope this helps!
1 Like