From a0e224f50edf1a3c44205b0d90a8e8e6494ba6c5 Mon Sep 17 00:00:00 2001 From: Sam Becker Date: Fri, 26 Apr 2024 11:41:13 -0500 Subject: [PATCH] Refine infinite swr behavior --- src/photo/InfinitePhotoScroll.tsx | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/photo/InfinitePhotoScroll.tsx b/src/photo/InfinitePhotoScroll.tsx index af9dcbc6..897ac6de 100644 --- a/src/photo/InfinitePhotoScroll.tsx +++ b/src/photo/InfinitePhotoScroll.tsx @@ -50,6 +50,8 @@ export default function InfinitePhotoScroll({ { revalidateFirstPage: false }, ); + const isLoadingOrValidating = isLoading || isValidating; + const isFinished = useMemo(() => data && data[data.length - 1]?.length < itemsPerPage , [data, itemsPerPage]); @@ -60,18 +62,26 @@ export default function InfinitePhotoScroll({ } }, [prefetch, isFinished, key, size, fetcher]); - const advance = useCallback(() => { - if (!isFinished) { + const advance = useCallback((advanceWhileStillVisible?: boolean) => { + if (!isFinished && !isLoadingOrValidating) { setSize(size => size + 1); + if (advanceWhileStillVisible) { + setTimeout(() => { + const rect = buttonContainerRef.current?.getBoundingClientRect(); + if (rect && rect.top >= 0) { + advance(true); + } + }, 1000); + } } - }, [isFinished, setSize]); + }, [isFinished, setSize, isLoadingOrValidating]); useEffect(() => { // Only add observer if button is rendered if (buttonContainerRef.current) { const observer = new IntersectionObserver(e => { if (triggerOnView && e[0].isIntersecting) { - advance(); + advance(true); } }, { root: null, @@ -102,16 +112,16 @@ export default function InfinitePhotoScroll({ className="-translate-y-32 pt-32 -mb-32" >