const { useRef, useEffect } = require('react')
const useLoadMoreOnScroll = (count, data, nextPage, fetch = () => null) => {
const hasMore = count > data?.length
const root = useRef()
const isLoadingMore = useRef(false)
useEffect(()=>{
root.current = document.querySelector('.root')
}, [])
useEffect(() => {
const onScroll = async () => {
const scrollPos = window.scrollY
if (
nextPage &&
!isLoadingMore.current &&
data?.length > 0 &&
hasMore &&
scrollPos + window.innerHeight + 500 >=
root.current.scrollHeight
) {
isLoadingMore.current = true
await fetch(
`${
window.location.search
? window.location.search + '&'
: '?'
}page=${nextPage}`
)
isLoadingMore.current = false
}
}
window.addEventListener('scroll', onScroll)
return () => {
window.removeEventListener('scroll', onScroll)
}
}, [data, nextPage, fetch, hasMore])
}
export default useLoadMoreOnScroll
Created
July 26, 2021 12:53
-
-
Save meetzaveri/704f84902bde2b803bd24b6b05d8f451 to your computer and use it in GitHub Desktop.
load more on scroll hook
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment