diff --git a/apps/material-react-table-docs/examples/infinite-scrolling/sandbox/src/TS.tsx b/apps/material-react-table-docs/examples/infinite-scrolling/sandbox/src/TS.tsx index bd9dbd997..62da3fa06 100644 --- a/apps/material-react-table-docs/examples/infinite-scrolling/sandbox/src/TS.tsx +++ b/apps/material-react-table-docs/examples/infinite-scrolling/sandbox/src/TS.tsx @@ -65,7 +65,7 @@ const fetchSize = 25; const Example = () => { const tableContainerRef = useRef(null); //we can get access to the underlying TableContainer element and react to its scroll events const rowVirtualizerInstanceRef = useRef(null); //we can get access to the underlying Virtualizer instance and call its scrollToIndex method - + const [currentMaxPages, setCurrentMaxPages] = useState(4); const [columnFilters, setColumnFilters] = useState( [], ); @@ -100,6 +100,7 @@ const Example = () => { initialPageParam: 0, getNextPageParam: (_lastGroup, groups) => groups.length, refetchOnWindowFocus: false, + maxPages: currentMaxPages, }); const flatData = useMemo( @@ -110,6 +111,22 @@ const Example = () => { const totalDBRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0; const totalFetched = flatData.length; + const handleScroll = useCallback(() => { + const containerElement = tableContainerRef.current; + if (containerElement) { + const { scrollHeight, scrollTop, clientHeight } = containerElement; + + if ( + scrollHeight - scrollTop - clientHeight < 400 && + !isFetching && + totalFetched < totalDBRowCount && + currentMaxPages < totalDBRowCount / fetchSize + ) { + setCurrentMaxPages((prevMaxPages) => prevMaxPages + 2); + } + } + }, [currentMaxPages, isFetching, totalFetched, totalDBRowCount]); + //called on scroll and possibly on mount to fetch more data as the user scrolls and reaches bottom of table const fetchMoreOnBottomReached = useCallback( (containerRefElement?: HTMLDivElement | null) => { @@ -138,6 +155,16 @@ const Example = () => { } }, [sorting, columnFilters, globalFilter]); + useEffect(() => { + const containerElement = tableContainerRef.current; + if (containerElement) { + containerElement.addEventListener('scroll', handleScroll); + return () => { + containerElement.removeEventListener('scroll', handleScroll); + }; + } + }, [handleScroll]); + //a check on mount to see if the table is already scrolled to the bottom and immediately needs to fetch more data useEffect(() => { fetchMoreOnBottomReached(tableContainerRef.current);