Black Lives Matter. Please consider donating to Black Girls Code today.

Callback being triggered on page reload - confused

Hello all,

I have an intensive data crunching task that should ONLY get triggered by a new file being selected with the upload button. I then have a graph that should be updated when either a new file is uploaded (and data crunched) OR a new dropdown value is selected.

My data crunching callback is setup as:

@app.callback(
    Output('intermediate-data', 'children'),
    [Input('upload-new', 'contents')],
    [State('upload-new', 'filename')])
def data_crunch(contents, filename):

and my graph update callback is setup as:

@app.callback(Output('My Graph', 'figure'), [Input('intermediate-data', 'children'),
                                                   Input('My Graph Dropdown', 'value')])
def update_graph(datasets, dropdown):

I have two issues:

  1. When I reload the webpage, the data_crunch function gets called. I only want it called when a file is uploaded via the upload button.
  2. When a new dropdown value is selected, the data_crunch function runs.

How do achieve my goal/solve these problems? At a loss for figuring out why it’s doing what it’s doing.

Thanks!

The dash-renderer currently send a None callback on page load to every callbacks.

You can prevent the update by raising PreventUpdate if the callback input value is None:

from dash.exceptions import PreventUpdate

@app.callback(...)
def on_click(n_clicks):
    if n_clicks is None:
        raise PreventUpdate

Hi Philippe,

Thanks for this! I’m a bit confused as to how to use it. In my case, do I add another input to my “update_graph” callback that is n_clicks? So like this:

@app.callback(Output('My Graph', 'figure'), [Input('intermediate-data', 'children'),
                                                   Input('My Graph Dropdown', 'value'),
                                                   Input('intermediate-data','n_clicks')])
def update_graph(datasets, dropdown, n_clicks):
    if n_clicks is None
        raise PreventUpdate

No that was just an example, you can check if the datasets is None.

Thanks! I ended up getting this working, thanks to your help.