I’ve built a Dash web app with an AG Grid table. The app dynamically loads data based on user inputs. In addition, when the user selects a row in the table, this also triggers updates. What I have been struggling with is how to have the table show the first row as the selected row whenever data is loaded into the table. The problem is that when the selected row state is changed, this triggers the callback a second time, and this second callback somehow unselects the row.
I’ve modified a Dash AG Grid example to illustrate my problem. How can this code be modified so that the first row is automatically selected when data is loaded into the table (by clicking on the button)?
import dash_ag_grid as dag
from dash import Dash, html, Input, Output, callback, no_update, ctx
import pandas as pd
app = Dash(__name__)
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]
app.layout = html.Div(
[
html.Button("Load Data", id="btn-load-data"),
dag.AgGrid(
id="row-selection-selected-rows",
columnDefs=columnDefs,
columnSize="autoSize",
dashGridOptions={"rowSelection": "single", "animateRows": False},
),
html.Pre(id="pre-row-selection-selected-rows", style={'text-wrap': 'wrap'})
],
)
@callback(
Output("row-selection-selected-rows", "rowData"),
Output("row-selection-selected-rows", "selectedRows"),
Output("pre-row-selection-selected-rows", "children"),
Input("btn-load-data", "n_clicks"),
Input("row-selection-selected-rows", "selectedRows")
)
def output_selected_rows(_, selected_rows):
print(ctx.triggered_id)
if ctx.triggered_id == "btn-load-data":
return df.to_dict("records"), df.head(1).to_dict("records"), ""
elif ctx.triggered_id == "row-selection-selected-rows":
selected_list = [f"{s['athlete']} ({s['year']})" for s in selected_rows]
msg = f"You selected the athlete{'s' if len(selected_rows) > 1 else ''}:\n{', '.join(selected_list)}" if selected_rows else "No selections"
return no_update, no_update, msg
return no_update, no_update, ""
if __name__ == "__main__":
app.run(debug=True)
@jinnyzor I see you’ve been helping with people’s struggles with AG Grid. Could you help with this?