import { __read } from "tslib";
import { useEffect } from 'react';
import { useTrackVisibility, } from 'react-intersection-observer-hook';
var DEFAULT_DELAY_IN_MS = 100;
export var useInfiniteScroll = function (_a) {
    var loading = _a.loading, hasNextPage = _a.hasNextPage, onLoadMore = _a.onLoadMore, rootMargin = _a.rootMargin, disabled = _a.disabled, _b = _a.delayInMs, delayInMs = _b === void 0 ? DEFAULT_DELAY_IN_MS : _b;
    var _c = __read(useTrackVisibility({
        rootMargin: rootMargin
    }), 2), ref = _c[0], _d = _c[1], rootRef = _d.rootRef, isVisible = _d.isVisible;
    var shouldLoadMore = !disabled && !loading && isVisible && hasNextPage;
    // eslint-disable-next-line consistent-return
    useEffect(function () {
        if (shouldLoadMore) {
            // When we trigger 'onLoadMore' and new items are added to the list,
            // right before they become rendered on the screen, 'loading' becomes false
            // and 'isVisible' can be true for a brief time, based on the scroll position.
            // So, it triggers 'onLoadMore' just after the first one is finished.
            // We use a small delay here to prevent this kind of situations.
            // It can be configured by hook args.
            var timer_1 = setTimeout(function () {
                onLoadMore();
            }, delayInMs);
            return function () {
                clearTimeout(timer_1);
            };
        }
    }, [onLoadMore, shouldLoadMore, delayInMs]);
    return [ref, { rootRef: rootRef }];
};
