Spaces:
Sleeping
Sleeping
File size: 1,475 Bytes
01d5a5d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import { Spin } from 'antd';
import classNames from 'classnames';
import { memo, useEffect, useRef } from 'react';
interface IProps {
className?: string;
scrollContainerId?: string;
loadMore: () => Promise<void>;
}
function LoadMore(props: IProps): JSX.Element {
const { loadMore, className, scrollContainerId = '#scrollContainer' } = props;
const eleRef = useRef<HTMLDivElement>(null);
const loadingRef = useRef<boolean>(false);
useEffect(() => {
if (!eleRef.current) {
return;
}
function callback(entries: IntersectionObserverEntry[]) {
entries.forEach((entry) => {
if (entry.isIntersecting && !loadingRef.current) {
loadingRef.current = true;
loadMore().finally(() => {
loadingRef.current = false;
});
}
});
}
const observer = new IntersectionObserver(callback, {
rootMargin: '50px',
root: document.querySelector(scrollContainerId),
threshold: [0.1]
});
const delayInMilliseconds = 500;
const timeoutId = setTimeout(() => {
if (eleRef.current) {
observer.observe(eleRef.current);
}
}, delayInMilliseconds);
return () => {
clearTimeout(timeoutId);
observer.disconnect();
};
}, [loadMore, scrollContainerId]);
return (
<div ref={eleRef} className={classNames('flex items-center justify-center', className)}>
<Spin />
</div>
);
}
export default memo(LoadMore);
|