I am making a dash app where there’s a dropdown. Depending on the value selected in the dropdown, I do some calculations in the backend and display a figure.
import dash
from dash.dependencies import Output, Event, Input
import dash_core_components as dcc
import dash_html_components as html
app.layout = html.Div([
dcc.Dropdown(
id='dataset-dropdown',
options=[
{'label': 'Option A', 'value': 'A'},
{'label': 'Option B', 'value': 'B'},
{'label': 'Option C', 'value': 'C'}
],
placeholder="Select an option",
),
html.Div(id='output-container'),
])
def function_to_draw(input_csv_file):
# make the figure
return plotly_fig_object
@app.callback(
dash.dependencies.Output('output-container', 'children'),
[dash.dependencies.Input('dataset-dropdown', 'value')])
def update_output(value):
if value=='A':
plotly_fig = function_to_draw('Data_of_A.csv')
return plotly_fig
elif value=='B':
plotly_fig = function_to_draw('Data_of_B.csv')
return plotly_fig
elif value=='C':
plotly_fig = function_to_draw('Data_of_C.csv')
return plotly_fig
return dcc.Graph(
id='plot_graph',
figure={
'data': plotly_fig
}
)
if __name__ == '__main__':
app.run_server(debug=True)
Now, it takes some time to do these backend calculations (5-10 seconds). So, what I want is, every time a value is clicked on the dropdown menu, it should show something like “Calculating…” or “Loading…” for those 5-10 seconds until the figure is displayed.
How do I do that?
I have tried adding a “placeholder” div to store the “Loading…” and added a callback function to display it upon click:
import dash
from dash.dependencies import Output, Event, Input
import dash_core_components as dcc
import dash_html_components as html
app.layout = html.Div([
dcc.Dropdown(
id='dataset-dropdown',
options=[
{'label': 'Option A', 'value': 'A'},
{'label': 'Option B', 'value': 'B'},
{'label': 'Option C', 'value': 'C'}
],
placeholder="Select an option",
),
html.Div(id='output-container'),
html.P(id="placeholder",children=["placeholder"]),
dcc.Interval(
id='clear-div',
interval=1*1000
),
])
@app.callback(
Output('placeholder', 'children'),
[Input(component_id='dataset-dropdown', component_property='value')],
events=[Event('clear-div', 'interval')]
)
def reset_div(input_data):
return "Calculating..."
@app.callback(
dash.dependencies.Output('output-container', 'children'),
[dash.dependencies.Input('dataset-dropdown', 'value')],
events=[Event('dataset-dropdown', 'click')])
def update_output(value):
if value=='A':
return "You selected A"
elif value=='B':
plotly_fig = function_to_draw('B')
return plotly_fig
elif value=='C':
plotly_fig = function_to_draw('C')
return plotly_fig
return dcc.Graph(
id='plot_graph',
figure={
'data': plotly_fig
}
)
if __name__ == '__main__':
app.run_server(debug=True)
But it doesn’t work as intended - it only shows the “Loading” on the initial dropdown selection. After that, it does not clear the output div to show “Loading…” in the subsequent dropdown selections; the existing figure in the output div persists.