Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(InfiniteScroll): fixed the double onActivate in the InfiniteScroll component #81

Merged
merged 5 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/components/InfiniteScroll/InfiniteScroll.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, {useState, useRef, useEffect} from 'react';
import {Loader} from '@gravity-ui/uikit';

import {block} from '../utils/cn';
import {useIntersection} from './hooks/useIntersection';
import {useOnIntersected} from './hooks/useOnIntersected';

import './InfiniteScroll.scss';

Expand All @@ -27,7 +27,6 @@ export const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
const [isActive, setIsActive] = useState(false);
const [bottomRef, setBottomRef] = useState<HTMLDivElement | null>(null);
const mounted = useRef(false);
const isBottomVisible = useIntersection(bottomRef);

useEffect(() => {
mounted.current = true;
Expand All @@ -37,7 +36,7 @@ export const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
};
}, []);

useEffect(() => {
useOnIntersected(bottomRef, () => {
const handleFetchData = async () => {
setIsActive(true);
await onActivate();
Expand All @@ -47,10 +46,10 @@ export const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
}
};

if (isBottomVisible && !isActive && !disabled) {
if (!isActive && !disabled) {
handleFetchData();
}
}, [isBottomVisible, onActivate, isActive, disabled]);
});

const renderedLoader = loader || (
<div className={b('loader')}>
Expand Down
19 changes: 0 additions & 19 deletions src/components/InfiniteScroll/hooks/useIntersection.ts

This file was deleted.

21 changes: 21 additions & 0 deletions src/components/InfiniteScroll/hooks/useOnIntersected.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {useEffect} from 'react';

export const useOnIntersected = (
element: Element | null,
onIntersected: () => void,
options?: IntersectionObserverInit,
) => {
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
onIntersected();
}
}, options);

if (element) {
observer.observe(element);
}

return () => (element === null ? undefined : observer.unobserve(element));
}, [element, onIntersected, options]);
};
Loading