Update figure by button with Input 'n_clicks' and State

I’m not sure why you get different behaviours on page load when using state. I can’t quite remember the rules on which callbacks get fired and with which values.

The second error you get is because your callback is implicitly returning None if you don’t enter the if statement, which gets converted to a javascript null which dcc.Graph tries to use as the figure for the graph but fails. Instead, you should specify a return value, or prevent an update. For example

@app.callback(
    Output("updated-graph", "figure"),
    [Input("update-button", "n_clicks")],
    [State("update-dropdown", "value")],
)
def update_figure(n_clicks, value):
    if n_clicks is None:
        return dash.no_update
    return {
        "data": [go.Scatter(x=[1, 2, 3], y=[int(value)] * 3)],
        "layout": go.Layout(
            title="number of clicks: " + str(n_clicks),
            yaxis={"title": "Selected value"},
        ),
    }

though you can also raise dash.exceptions.PreventUpdate or simply return some default figure of your choice if you prefer.

1 Like