angelsarebeautiful
angelsarebeautiful

Reputation: 118

Python Dash - Combining two callback functions

I am trying to create a dash app that consists of a table. The table has 2 functions: adding empty rows the user can fill in, and refreshing the app with the newest info in an underlying csv file. When I run my app, I get this error: You have already assigned a callback to the output with ID "table" and property "data". An output can only have a single callback function. Try combining your inputs and callback functions together into one function.

Is there any way to combine the following two callback functions into one?

@app.callback(dash.dependencies.Output('table', 'data'),
              [dash.dependencies.Input('refresh-button', 'n_clicks')])
def refresh(n_clicks):    
    if n_clicks > 0:
        data = pd.read_csv(partnernship_data).to_dict('records')
    return data

@app.callback(
        Output('table', 'data'),
        [Input('editing-rows-button', 'n_clicks')],
        [State('table', 'data'),
         State('table', 'columns')])
def add_row(n_clicks, rows, columns):
    if n_clicks > 0:
        rows.append({c['id']: '' for c in columns})
    return rows

Upvotes: 4

Views: 3346

Answers (1)

coralvanda
coralvanda

Reputation: 6586

I think what you want here is callback that uses the callback context feature (see this page of the docs for that). I haven't run this, but hopefully it's pretty close.

@app.callback(
        Output('table', 'data'),
        [Input('editing-rows-button', 'n_clicks'),
         Input('refresh-button', 'n_clicks')],
        [State('table', 'data'),
         State('table', 'columns')])
def add_row(edit_rows_button, refresh_button, rows, columns):
    button_id = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    if button_id == 'editing-rows-button' and edit_rows_button:
        rows.append({c['id']: '' for c in columns})
        return rows
    elif button_id == 'refresh-button' and refresh_button:
        data = pd.read_csv(partnernship_data).to_dict('records')
        return data
    else:
        raise dash.exceptions.PreventUpdate

Upvotes: 3

Related Questions