File size: 1,129 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { useState, useEffect, useCallback, RefObject } from 'react';

export const useInfiniteScroll = ({
  ref,
  hasMore,
  onLoadMore,
}: {
  onLoadMore: Function;
  hasMore: boolean;
  ref: RefObject<HTMLElement>;
}): [boolean, () => void] => {
  const [isFetching, setIsFetching] = useState(false);
  const handleScroll = useCallback(() => {
    if (ref.current!.scrollTop === 0 && isFetching === false && hasMore) {
      // starts to fetch if scrolled to top, fetching is not in progress and has more data
      setIsFetching(true);
    }
  }, [ref, isFetching, hasMore]);

  useEffect(() => {
    const elem = ref.current;

    if (!elem) {
      return;
    }

    elem.addEventListener('scroll', handleScroll);

    return () => {
      elem!.removeEventListener('scroll', handleScroll);
    };
  }, [ref, handleScroll]);

  // loads more if fetching has started
  useEffect(() => {
    if (isFetching) {
      onLoadMore();
    }
  }, [isFetching, onLoadMore]);

  const stopFetching = useCallback(() => {
    setIsFetching(false);
  }, []);

  return [isFetching, stopFetching];
};

export default useInfiniteScroll;