Spaces:
Running
Running
| ts | |
| import { useEffect, useRef, useState } from 'react' | |
| export function useInfiniteScroll(callback: () => void, options?: IntersectionObserverInit) { | |
| const [isFetching, setIsFetching] = useState(false) | |
| const sentinelRef = useRef<HTMLDivElement | null>(null) | |
| useEffect(() => { | |
| if (!sentinelRef.current) return | |
| const observer = new IntersectionObserver( | |
| entries => { | |
| if (entries[0].isIntersecting) setIsFetching(true) | |
| }, | |
| options | |
| ) | |
| observer.observe(sentinelRef.current) | |
| return () => observer.disconnect() | |
| }, [options]) | |
| useEffect(() => { | |
| if (!isFetching) return | |
| callback() | |
| }, [isFetching, callback]) | |
| return { sentinelRef, isFetching, setIsFetching } | |
| } | |
| </html> |