Update graph only after button is clicked

I have a dash DatePickerRange component and a refresh button in my dash app.
I want the graphs to be updated as per the new dates from the DatePickerRange input only after the user clicks the refresh button.
I wrote a callback function for this which takes the start_date, end_date from the DateRangePicker as Input and also the n_clicks from the refresh button.

Code:

@app.callback(
    Output(component_id='newusers bar graph',component_property='figure'),
    Input(component_id='date picker',component_property='start_date'),
    Input(component_id='date picker',component_property='end_date'),
    Input(component_id='refresh button',component_property='n_clicks')
)
def update_graph(start_date,end_date,n):
    if n is None:
        return dash.no_update
    else:
        return bar_graph(start_date,end_date)

This works fine when the app is loaded for the first time and the graph isn’t updated until the n_clicks value changes from None. But after that the graphs are updated continuously whenever the dates inputs are changed which makes sense as the n_clicks are not None now. Is it possible to save the last value of the n_clicks and update the graph only after the last value is changed.

If I understand correctly, you do not want the graph to refresh if the user selects a new start_date or end_date on the date picker, but only when he clicks the button, correct?

If so, use a State instead of an Input for the date picker. Your callback would then start like this (you may need to import State from dash.dependencies):

@app.callback(
    Output(component_id='newusers bar graph',component_property='figure'),
    Input(component_id='refresh button',component_property='n_clicks'),
    State(component_id='date picker',component_property='start_date'),
    State(component_id='date picker',component_property='end_date'),
)
def update_graph(n,start_date,end_date):

Now, changes to start_date or end_date won’t trigger your callback, only clicks on the refresh button will.

If this answers your question, I highly recommend reading the Dash Tutorial to learn the basics. This subject is covered in chapter 3: Basic Callbacks | Dash for Python Documentation | Plotly

Thank you @MichelH :slightly_smiling_face: