UNPKG

@elacity-js/uikit

Version:

React / Material UI Design kit for Elacity project

48 lines (45 loc) 2.17 kB
import { __rest } from '../node_modules/tslib/tslib.es6.js'; import React__default from 'react'; import { uid } from '@elacity-js/lib'; import { throttle } from 'lodash'; import { useInView } from '../node_modules/react-intersection-observer/react-intersection-observer.modern.mjs.js'; import useMounted from './useMounted.js'; var useInfiniteQuery = ({ useQuery, query, index, pageSize, onRequestId, }) => { const requestGroupId = React__default.useRef(uid()); const mounted = useMounted(); const [currentPage, setCurrent] = React__default.useState(index || 1); const { ref, inView } = useInView({ threshold: 0, rootMargin: '20px', initialInView: false, }); const _a = useQuery(Object.assign(Object.assign({}, query), { from: (currentPage - 1) * pageSize, count: pageSize }), { skip: currentPage === 0 }), { isLoading, data, requestId } = _a, currentResult = __rest(_a, ["isLoading", "data", "requestId"]); const loadNext = React__default.useCallback(throttle(() => { // console.log('[LazyLoad] Loading next range', currentPage + 1); setCurrent((prev) => prev + 1); }, 500), []); // load the next range of data when the witness is showing in the viewport React__default.useEffect(() => { if (mounted && inView && !isLoading && currentPage * pageSize < (currentResult === null || currentResult === void 0 ? void 0 : currentResult.total)) { loadNext(); } }, [inView]); React__default.useEffect(() => { if (requestId) { onRequestId === null || onRequestId === void 0 ? void 0 : onRequestId(requestGroupId.current, requestId); } }, [requestId]); return { ref, inView, data: data || [], total: (currentResult === null || currentResult === void 0 ? void 0 : currentResult.total) || 0, isLoading, requestId, currentPage, offset: (currentResult === null || currentResult === void 0 ? void 0 : currentResult.offset) || 0, rewindZero: () => setCurrent(1), }; }; export { useInfiniteQuery as default }; //# sourceMappingURL=useInfiniteQuery.js.map