fixed code
This commit is contained in:
27
src/hooks/useInfiniteScroll.jsx
Normal file
27
src/hooks/useInfiniteScroll.jsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { useRef, useCallback } from "react";
|
||||
|
||||
/**
|
||||
* Универсальный хук для бесконечного скролла через IntersectionObserver.
|
||||
* Возвращает ref, который нужно повесить на сентинел-элемент в конце списка.
|
||||
*
|
||||
* @param {Function} onIntersect — вызывается, когда сентинел попадает в вьюпорт
|
||||
* @param {boolean} enabled — можно ли сейчас триггерить подгрузку
|
||||
*/
|
||||
export function useInfiniteScroll(onIntersect, enabled) {
|
||||
const observerRef = useRef(null);
|
||||
|
||||
const sentinelRef = useCallback(node => {
|
||||
if (!enabled) return;
|
||||
if (observerRef.current) observerRef.current.disconnect();
|
||||
|
||||
observerRef.current = new IntersectionObserver(entries => {
|
||||
if (entries[0].isIntersecting && enabled) {
|
||||
onIntersect();
|
||||
}
|
||||
}, { rootMargin: "200px" });
|
||||
|
||||
if (node) observerRef.current.observe(node);
|
||||
}, [enabled, onIntersect]);
|
||||
|
||||
return sentinelRef;
|
||||
}
|
||||
Reference in New Issue
Block a user