prometheus
50 строк · 1.5 Кб
1import { ComponentType, useEffect, useState } from 'react';
2import InfiniteScroll from 'react-infinite-scroll-component';
3
4const initialNumberOfItemsDisplayed = 50;
5
6export interface InfiniteScrollItemsProps<T> {
7items: T[];
8}
9
10interface CustomInfiniteScrollProps<T> {
11allItems: T[];
12child: ComponentType<InfiniteScrollItemsProps<T>>;
13}
14
15// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
16const CustomInfiniteScroll = <T,>({ allItems, child }: CustomInfiniteScrollProps<T>) => {
17const [items, setItems] = useState<T[]>(allItems.slice(0, 50));
18const [index, setIndex] = useState<number>(initialNumberOfItemsDisplayed);
19const [hasMore, setHasMore] = useState<boolean>(allItems.length > initialNumberOfItemsDisplayed);
20const Child = child;
21
22useEffect(() => {
23setItems(allItems.slice(0, initialNumberOfItemsDisplayed));
24setHasMore(allItems.length > initialNumberOfItemsDisplayed);
25}, [allItems]);
26
27const fetchMoreData = () => {
28if (items.length === allItems.length) {
29setHasMore(false);
30} else {
31const newIndex = index + initialNumberOfItemsDisplayed;
32setIndex(newIndex);
33setItems(allItems.slice(0, newIndex));
34}
35};
36
37return (
38<InfiniteScroll
39next={fetchMoreData}
40hasMore={hasMore}
41loader={<h4>loading...</h4>}
42dataLength={items.length}
43height={items.length > 25 ? '75vh' : ''}
44>
45<Child items={items} />
46</InfiniteScroll>
47);
48};
49
50export default CustomInfiniteScroll;
51