Files
supabase/apps/studio/hooks/misc/useInfiniteScroll.ts
Charis 180ce515f6 style: require @ imports and sort imports for studio/hooks (#44444)
* **Chores**
* Updated internal module import paths across hook files to use
standardized path aliases for improved code consistency and
maintainability.
2026-04-01 11:48:02 -04:00

46 lines
1.2 KiB
TypeScript

import { UIEvent, useCallback, useRef } from 'react'
import { isAtBottom } from '@/lib/helpers'
interface UseInfiniteScrollOptions {
isLoading?: boolean
isFetchingNextPage?: boolean
hasNextPage?: boolean
fetchNextPage: (options?: { cancelRefetch?: boolean }) => void
}
/**
* Returns a scroll handler that triggers fetchNextPage when the user scrolls
* to the bottom of a scrollable container. Includes horizontal scroll detection
* to avoid triggering loads when the user scrolls horizontally.
*/
export function useInfiniteScroll({
isLoading = false,
isFetchingNextPage = false,
hasNextPage = false,
fetchNextPage,
}: UseInfiniteScrollOptions) {
const xScroll = useRef(0)
return useCallback(
(event: UIEvent<HTMLDivElement>) => {
const isScrollingHorizontally = xScroll.current !== event.currentTarget.scrollLeft
xScroll.current = event.currentTarget.scrollLeft
const shouldFetchNextPage =
!isLoading &&
!isFetchingNextPage &&
!isScrollingHorizontally &&
isAtBottom(event) &&
hasNextPage
if (!shouldFetchNextPage) {
return
}
fetchNextPage({ cancelRefetch: false })
},
[isLoading, isFetchingNextPage, hasNextPage, fetchNextPage]
)
}