@spaced-out/ui-design-system
Version:
Sense UI components library
56 lines (55 loc) • 2.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useInfiniteScroll = useInfiniteScroll;
var React = _interopRequireWildcard(require("react"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function useInfiniteScroll(_ref) {
let {
itemSize,
threshold,
itemsLength,
hasNextPage,
loadMoreItems,
containerHeight,
isVariableSizeList
} = _ref;
const [isLoading, setIsLoading] = React.useState(false);
const loadingRef = React.useRef(false);
const handleLoadMore = React.useCallback(async () => {
if (!hasNextPage || isLoading || loadingRef.current) {
return;
}
loadingRef.current = true;
setIsLoading(true);
try {
await loadMoreItems();
} catch (err) {
console.error('Error loading more items:', err);
} finally {
loadingRef.current = false;
setIsLoading(false);
}
}, [hasNextPage, isLoading, loadMoreItems]);
return React.useCallback(_ref2 => {
let {
scrollOffset,
scrollDirection
} = _ref2;
if (scrollDirection !== 'forward') {
return;
}
let totalSize = 0;
if (isVariableSizeList && typeof itemSize === 'function') {
for (let i = 0; i < itemsLength; i++) {
totalSize += itemSize(i);
}
} else if (typeof itemSize === 'number') {
totalSize = itemsLength * itemSize;
}
if (scrollOffset > totalSize - containerHeight - threshold && hasNextPage && !isLoading) {
handleLoadMore();
}
}, [itemSize, threshold, isLoading, itemsLength, hasNextPage, handleLoadMore, containerHeight, isVariableSizeList]);
}