I am trying to automatically resize my columns to fit their contents using an autoSizeAll
function I wrote. I want this to happen every time the grid’s data is done rendering. This is because the user can click a ‘get data’ button that re-populates the grid with different data at any point in time.
My autoSizeAll
function works on its own, but I am having an issue of calling it too early (before the data is done rendering), resulting in weird/no column autosizing.
Someone was able to help me get it to work by using setTimeout
with an arbitrary time, but this seems like a solution that isn’t completely reliable:
useEffect(() => {
if (rowData && rowData.length > 0) {
setTimeout(() => autosizeAll(), 250)
}
}, [columnDefs, rowData, autoSizeAll])
So the question is: Is there a way I can reliably check if the grid has rendered its data? AG-Grid’s firstDataRendered
event works perfectly for the first render but doesn’t trigger after that. I have also tried onRowDataUpdated
as well as not using the timeout, but the autosizing seems to trigger before the data is done rendering, sizing the columns in a weird way.
I would really appreciate some help! Thanks 🙂
Edit: Here is the code for autoSizeAll
:
const autoSizeAll = useCallback(() => {
const allColumnIds = [];
gridRef.current.columnApi.getColumns().forEach((column) => {
allColumnIds.push(column.colId);
});
gridRef.current.columnApi.autoSizeColumns(allColumnIds);
}, []);
3
Answers
you can use the AG-Grid event:
gridReady
. ThegridReady
event runs once the grid is fully initialized and ready to be interacted with.Here is the code:
If you have any question or this doesn’t work, comment below. Hope this helps.
AgGridReact have a props processRowPostCreate which takes a callback
Can you please try calling your custom function autosizeAll from here and see if it works?
Also definition of autosizeAll would help debug this issue more.
If you have any questions please let me know.
Trying again 🙂
To get notified by onRowDataUpdated event, we should update our data using applyTransaction
Put this as a prop in your AgGridReact component
Update your data using applyTransaction like below
By this way, you ensure your grid is going to be resized after you update your data
Check this plunker: https://plnkr.co/edit/1xcD5c6IKlSTOhpo?preview
Hit on Update Top 2, see the grid resize and start digging through 😀