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

43 lines
1.1 KiB
TypeScript
Raw Normal View History

import { useEffect, useRef, useState } from 'react'
2022-02-11 17:24:33 +00:00
export const useFetchMore = (callback: () => void, delay = 500): void => {
const [first, setFirst] = useState(true)
2022-02-11 17:24:33 +00:00
const throttleTimeout = useRef<NodeJS.Timeout | undefined>(undefined)
useEffect(() => {
if (typeof window === 'undefined') {
2022-02-11 17:24:33 +00:00
return
}
const callbackInternal = (): void => {
const {
scrollTop,
scrollHeight,
clientHeight
} = window.document.documentElement;
2022-02-11 17:24:33 +00:00
if (scrollTop + clientHeight >= scrollHeight - (scrollHeight / 3)) {
callback()
}
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
}
}, [callback, delay, first, setFirst])
2022-02-11 17:24:33 +00:00
}