1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 04:46:40 +07:00

fixed lab infinite scroll

This commit is contained in:
Fedor Katurov 2022-12-19 18:27:51 +06:00
parent de4207ab63
commit f7cd6316f5
4 changed files with 103 additions and 23 deletions

View file

@ -0,0 +1,48 @@
import { useCallback, useEffect, useMemo } from 'react';
import { throttle } from 'throttle-debounce';
import { useWindowSize } from './useWindowSize';
interface Options {
active?: boolean;
threshold?: number;
}
export const useScrollEnd = (
item: Element | Element[] | undefined | null,
callback?: () => void,
{ active = true, threshold = 1.5 }: Options = {},
) => {
const debouncedCallback = useMemo(
() => callback && throttle(1000, callback),
[callback],
);
const { innerHeight } = useWindowSize();
useEffect(() => {
if (!item || !active || !debouncedCallback) return;
const items = Array.isArray(item) ? item : [item];
const positions = items.map((it) => {
const { top, height } = it.getBoundingClientRect();
return top + window.scrollY + height;
});
const eventHandler = () => {
if (
!positions.some(
(it) => it < window.scrollY + window.innerHeight * threshold,
)
)
return;
debouncedCallback();
};
window.addEventListener('scroll', eventHandler);
return () => window.removeEventListener('scroll', eventHandler);
}, [item, active, innerHeight, debouncedCallback]);
};