Search code examples
ag-gridag-grid-react

AGGrid - Pause updates to grid when user is scrolling


I'm using AgGrid in React which gets frequent updates from a server. If I wanted to scroll down to analyze a specific row, it's made difficult as the grid is constantly adding new rows and pushing the row I want to view down.

So to keep the row in view I have to continue scrolling. This isn't the best UX.

One solution would be to pause updates if the user is not scrolled to the top. But once they do scroll to the top, all the updates would come in at once which isn't great UX either.

I'm trying to allow the grid to continue updating but also keep the scroll position locked with the rows they are looking at. Is this possible with AgGrid?


Solution

  • Here's the custom solution I came up with:

    if (transaction.add.length > 0 || transaction.update.length > 0 || transaction.remove.length > 0) {
            try {
                const gridApi = gridApiRef.current;
                const firstVisibleRow = gridApi.getFirstDisplayedRowIndex();
                const lastVisibleRow = gridApi.getLastDisplayedRowIndex();
                const isTopRow = firstVisibleRow === 0;
    
                // Calculate the index to keep in view before applying the transaction
                const indexToKeepInView = isTopRow ? 0 : Math.floor((firstVisibleRow + lastVisibleRow) / 2);
    
                // Apply the transaction
                gridApi.applyTransaction(transaction);
    
                if (!isTopRow) {
                    // Adjust the index based on the number of rows added
                    const adjustedIndex = indexToKeepInView + transaction.add.length;
                    console.log(`Scroll position is not at the top. Ensuring index is visible: ${adjustedIndex}`);
                    console.log(`Amount of adds: ${transaction.add.length}`);
                    // Use setTimeout to ensure the DOM has updated before scrolling
                    setTimeout(() => {
                        gridApi.ensureIndexVisible(adjustedIndex, 'middle');
                    }, 0);
                }
            } catch (error) {
                console.error('Grid error:', error);
            }
        }
    

    Any time the makes an update, it checks to see if the top visible row is the first row, if it is not we know we are scrolled down. We use ensureIndexVisible to scroll to the index right after applying the transaction to keep the same rows on the screen.