Multiple DataTables and Callback problem


#1

My plan is to show a DataTable and let the user select a row. The selection will be used to populate a second DataTable based on a database query. When user selects a row in the second DataTable a new query will be run and data will be shown elsewhere (in a graph or in a third Data Table). I’m able to get the first callback to work, populating the second DataTable based on user selection in the first DataTable. When adding a second Callback to capture selections in second DataTable - nothing is working.

Where did I go wrong? Suggestions are much appreciated.

Sample code attached. Second callback is commented out in order to show that one callback is working.

import dash
import dash_html_components as html
import dash_table
import pandas as pd

pick = pd.DataFrame({
    'c1': ['a', 'b'],
    'c2': [0, 1] })

dataset_a = pd.DataFrame({
    'c1': ['a', 'b', 'c', 'd', 'e', 'f'],
    'c2': [2, 3, 1, 5, 7, 4] })

dataset_b = pd.DataFrame({
    'c1': ['g', 'h', 'i', 'j', 'k', 'l'],
    'c2': [8, 7, 9, 6, 3, 1 })

db = [dataset_a, dataset_b]

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.Div('Select 1'),
    dash_table.DataTable(
        id='table_1',
        columns=[{'id': 'c1', 'name': 'Select row'},
                 {'id': 'c2', 'hidden': True}],
        data=pick.to_dict('rows'),
        style_cell={'textAlign': 'left'},
        row_selectable="single",
    ),
    html.Div('Select 2'),
    dash_table.DataTable(
        id='table_2',
        columns=[{'id': 'c1', 'name': 'Select row'},
                 {'id': 'c2', 'hidden': True}],
        data=[{}],
        style_cell={'textAlign': 'left'},
        row_selectable="single",
    ),
    html.Div('Selection:'),
    html.Div(id='result'),
])


@app.callback(
    dash.dependencies.Output('table_2', 'data'),
    [dash.dependencies.Input('table_1', 'derived_virtual_selected_rows')])
def table_1_pick(selected_rows):
    if selected_rows:
        row = selected_rows[0]
        return db[row].to_dict("rows")
    else:
        return None


#@app.callback(
#    dash.dependencies.Output('result', 'children'),
#    [dash.dependencies.Input('table_2', 'derived_virtual_selected_rows')])
def table_2_pick(selected_rows):
    if selected_rows:
        row = selected_rows[0]
        return 'Selected row %s' % row
    else:
        return 'Nothing selected'


if __name__ == "__main__":
    app.run_server(debug=True)