简体   繁体   中英

Ag-Grid does not navigate to next page on adding row dynamically

I am using Ag-grid used in my React app mapped to some state.

const [myGridData, setMyGridData] = useState([]);

<MyAgGrid
    rowData={myGridData}
    pagination
    paginationPageSize={5}
    {...props}
/>

Now, I have a form which takes user input and adds a new row dynamically to the grid.

So on saving this form, below code is invoked

setMyGridData(current => [...current, newRowData]);
if (gridApi && gridApi.getDisplayedRowCount() >= gridApi.paginationGetPageSize()) {
    gridApi.paginationGoToPage(parseInt((gridApi.getDisplayedRowCount() / gridApi.paginationGetPageSize())) + 1);
}

The page size is set to 5. So while I save the 6th record, I want that the grid navigate to page 2 programatically, so that the user sees the new record in the grid.

But here while the grid does add the 6th row, it does not navigate to page 2 and I have to navigate manually to see the 6th record. However, if I am on page 1 and add the next record (ie 7th row), it then does navigate to page 2.

So it seems like that for the 6th record, the 2nd page is not yet ready/created.

Please help.

React state won't have flowed into the ag-grid component immediately after calling the setState function, due the nature of the react lifecycle. (This means that ag-grid won't know it has that extra row yet at the time you're calling the function)

You could skip the react lifecycle and instead set the row data directly into the grid with api.setRowData, however the approach which leans more into the react lifecycle would be to instead use an effect like so:

const [myGridData, setMyGridData] = useState([]);

useLayoutEffect(() => {
    gridApi.paginationGoToPage(parseInt((gridApi.getDisplayedRowCount() / gridApi.paginationGetPageSize())) + 1);
}, [myGridData]);

<MyAgGrid
    rowData={myGridData}
    pagination
    paginationPageSize={5}
    {...props}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM