/
lizardking
/
react_final
Обзор
Документация
Войти
/
lizardking
/
react_final
Код
Запросы
1
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
old
src/shared/ui/LoadMore/hooks/useLoadMore.ts
48 строк
1 KB
LizardKing
Initial commit
22 ноя 2025, 15:56
22 ноя 2025, 15:56
0df0d9e
Код
Авторство
О чём код?
import type { RefObject } from 'react' import { useCallback, useLayoutEffect } from 'react' import { useProducts } from '../../../store/hooks/useProducts' import { productsActions, productsSelectors } from '../../../store/slices/products' import { useAppDispatch, useAppSelector } from '../../../store/utils' type UseLoadMoreParams = { ref: RefObject<HTMLElement | null> } export const useLoadMore = ({ ref }: UseLoadMoreParams) => { const dispatch = useAppDispatch() const { products, isFetching, productsCount } = useProducts() const page = useAppSelector(productsSelectors.getPage) const isEndOfList = products.length >= productsCount const fetchMoreProducts = useCallback(() => { if (!isEndOfList && !isFetching) { dispatch(productsActions.setPage(page + 1)) } }, [isEndOfList, isFetching, page, dispatch]) useLayoutEffect(() => { let observer: IntersectionObserver | undefined if (!isEndOfList && products.length) { const options: IntersectionObserverInit = { threshold: 0.5 } const callback: IntersectionObserverCallback = (entries) => { if (entries[0]?.isIntersecting) { fetchMoreProducts() } } observer = new IntersectionObserver(callback, options) if (ref.current) { observer.observe(ref.current) } } return () => { observer?.disconnect() } }, [fetchMoreProducts, isEndOfList, products.length, ref]) return { isEndOfList, isFetching } }