0

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 (i.e. 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.

4
  • Why don't you try to sort by newest date? So user can see the new data on page 1 Commented Jul 25, 2022 at 8:32
  • yeah, that can be done...but am not really capturing the date added in this case...so need to programatically paginate once page limit is reached Commented Jul 25, 2022 at 9:43
  • Check ag-grid Custom Paging section. When new row is added try using api.paginationGoToPage(4) to change page number Commented Jul 25, 2022 at 13:44
  • yeah, I am using paginationGoToPage , but for some reason, it does not seem to be working in the scenario I have mentioned Commented Jul 25, 2022 at 14:32

1 Answer 1

0

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} /> 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot...Actually I had earlier tried with the useEffect and it didn't work...I tried now with the useLayoutEffect and that is also not working....Also I'll prefer via the React lifecyle and would ideally want to avoid calling setRowData directly
Is there some reason why paginationGoToLastPage wouldn't work instead?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.