omnivore/packages/web/lib/hooks/useFetchMoreScroll.tsx

43 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

import { useEffect, useRef, useState } from 'react'
2022-02-11 17:24:33 +00:00
export const useFetchMore = (fetchNextPage: () => void, delay = 500): void => {
const [first, setFirst] = useState(true)
2024-08-17 06:19:26 +00:00
const [lastScrollTop, setLastScrollTop] = useState(0)
2022-02-11 17:24:33 +00:00
const throttleTimeout = useRef<NodeJS.Timeout | undefined>(undefined)
useEffect(() => {
const callbackInternal = (): void => {
const { scrollTop, scrollHeight, clientHeight } =
window.document.documentElement
2024-08-17 06:19:26 +00:00
const direction = scrollTop > lastScrollTop ? 'down' : 'up'
setLastScrollTop(scrollTop)
if (
direction == 'down' &&
scrollTop + clientHeight >= scrollHeight - scrollHeight / 3
) {
fetchNextPage()
}
2024-08-17 06:19:26 +00:00
2022-02-11 17:24:33 +00:00
throttleTimeout.current = undefined
}
const handleScroll = () => {
if (first) {
setFirst(false)
2022-02-11 17:24:33 +00:00
callbackInternal()
return
}
if (typeof throttleTimeout.current === 'undefined') {
throttleTimeout.current = setTimeout(callbackInternal, delay)
}
}
window.addEventListener('scroll', handleScroll)
2022-02-11 17:24:33 +00:00
return () => {
window.removeEventListener('scroll', handleScroll)
2022-02-11 17:24:33 +00:00
}
}, [fetchNextPage, delay, first, setFirst])
2022-02-11 17:24:33 +00:00
}