'Show loading state for few seconds if new data comes and then show the figure, else keep the figure as it is in Dash app python
I'm building a data dashboard, and one of the requirements is to refresh the dashboard whenever new data is coming. Data is being checked from the database at a 30-second interval along with max timestamps of the data. What I want is if the max timestamp is > current timestamp then load the charts with loading state or else keep the charts as it is.
As of now I'm using alerts for updating the user that new data has arrived. Why I want the loading state instead of alerts is because it would be nice for end-user to get notified by the loading state of the chart instead of the alerts.
Here is the sample working code:
alert = dbc.Alert(
"New Data Incoming!",
id=" test-alert-auto",
# is_open=True,
duration=5000,
color="danger",
)
max_datetime = 0
app.layout = html.Div([html.Div(id="load", children=[]),
dcc.Interval(
id="interval-component",
interval=30 * 1000,
n_intervals=0, # in milliseconds
),
html.Div(
[
dbc.Card(
[
dbc.CardBody(
[
html.Div(
[
dbc.Button(
"Notifications",
id="test-toggle-auto",
className="mr-1",
),
html.Hr(),
html.Div(id="the-alert", children=[])
# dbc.Alert(
# "Hello! I am an auto-dismissing alert!",
# id=" test-alert-auto",
# is_open=True,
# duration=5000,
# ),
],
# style={"padding": "2rem 2rem"},
)
]
)
]
)
],
style={
"float": "right",
"margin-bottom": "2rem",
"margin-top": "1rem",
"margin-right": "30px",
},
)])
@app.callback(
[
Output("load", "children"),
Output("the-alert", "children"),
],
[Input("submit-button", "n_clicks"), Input("interval-component", "n_intervals")],
[
State("region", "value"),
State("my-date-picker-range", "start_date"),
State("my-date-picker-range", "end_date"),
],
)
def update_graph(
n_clicks,
n_intervals,
region_name,
start_date,
end_date,
):
### Gets the data from the database
### Gets the list of timestamp
### plots the data and generates figure object
max_timestamp_list = []
if max_datetime == 0:
max_datetime = max(max_timestamp_list)
return fig, alert
if max_datetime == max(max_timestamp_list):
return fig, dash.no_update
if max_datetime < max(max_timestamp_list):
max_datetime = max(max_timestamp_list)
return fig, alert
if __name__ == '__main__':
app.run_server(debug=True)
I consider myself a naïve in dash, any help suggestion or code would be appreciated.
Solution 1:[1]
To solve this problem I used dcc.Loading state from the Dash core components. Dash has some good examples on dcc.Loading here: https://dash.plotly.com/dash-core-components/loading
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yadvendar Singh |
