2022-06-17 22:59:41 +00:00
|
|
|
import { useEffect, useRef, useState } from 'react'
|
2022-02-11 17:24:33 +00:00
|
|
|
|
2022-06-17 22:59:41 +00:00
|
|
|
export const useFetchMore = (callback: () => void, delay = 500): void => {
|
2022-03-09 05:57:12 +00:00
|
|
|
const [first, setFirst] = useState(true)
|
2022-02-11 17:24:33 +00:00
|
|
|
const throttleTimeout = useRef<NodeJS.Timeout | undefined>(undefined)
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-17 22:59:41 +00:00
|
|
|
if (typeof window === 'undefined') {
|
2022-02-11 17:24:33 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const callbackInternal = (): void => {
|
|
|
|
|
const {
|
|
|
|
|
scrollTop,
|
|
|
|
|
scrollHeight,
|
|
|
|
|
clientHeight
|
2022-06-17 22:59:41 +00:00
|
|
|
} = 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) {
|
2022-03-09 05:57:12 +00:00
|
|
|
setFirst(false)
|
2022-02-11 17:24:33 +00:00
|
|
|
callbackInternal()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if (typeof throttleTimeout.current === 'undefined') {
|
|
|
|
|
throttleTimeout.current = setTimeout(callbackInternal, delay)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-17 22:59:41 +00:00
|
|
|
window.addEventListener('scroll', handleScroll)
|
2022-02-11 17:24:33 +00:00
|
|
|
|
|
|
|
|
return () => {
|
2022-06-17 22:59:41 +00:00
|
|
|
window.removeEventListener('scroll', handleScroll)
|
2022-02-11 17:24:33 +00:00
|
|
|
}
|
2022-06-17 22:59:41 +00:00
|
|
|
}, [callback, delay, first, setFirst])
|
2022-02-11 17:24:33 +00:00
|
|
|
}
|