-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathuseInfiniteScroll.ts
More file actions
129 lines (101 loc) · 3.9 KB
/
useInfiniteScroll.ts
File metadata and controls
129 lines (101 loc) · 3.9 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { isEqual } from 'lodash';
import { UseLazyQuery /*, UseQueryStateOptions*/ } from '@reduxjs/toolkit/dist/query/react/buildHooks';
import { QueryDefinition } from '@reduxjs/toolkit/query';
const SCROLL_POSITION_GAP = 400;
type InfinityListArgs = Partial<Record<string, unknown>>;
type ListResponse<DataItem> = DataItem[];
type UseInfinityParams<DataItem, Args extends InfinityListArgs> = {
useLazyQuery: UseLazyQuery<QueryDefinition<Args, any, any, ListResponse<DataItem>, any>>;
args: { limit?: number } & Args;
getPaginationParams: (listItem: DataItem) => Partial<Args>;
// options?: UseQueryStateOptions<QueryDefinition<Args, any, any, Data[], any>, Record<string, any>>;
};
export const useInfiniteScroll = <DataItem, Args extends InfinityListArgs>({
useLazyQuery,
getPaginationParams,
// options,
args,
}: UseInfinityParams<DataItem, Args>) => {
const [data, setData] = useState<ListResponse<DataItem>>([]);
const scrollElement = useRef<HTMLElement>(document.documentElement);
const isLoadingRef = useRef<boolean>(false);
const lastRequestParams = useRef<TRunsRequestParams | undefined>(undefined);
const [disabledMore, setDisabledMore] = useState(false);
const { limit, ...argsProp } = args;
const lastArgsProps = useRef<Partial<Args>>(null);
const [getItems, { isLoading, isFetching }] = useLazyQuery({ ...args } as Args);
const getDataRequest = (params: Args) => {
lastRequestParams.current = params;
return getItems({
limit,
...params,
} as Args).unwrap();
};
const getEmptyList = () => {
isLoadingRef.current = true;
setData([]);
getDataRequest(argsProp as Args).then((result) => {
setDisabledMore(false);
setData(result as ListResponse<DataItem>);
isLoadingRef.current = false;
});
};
useEffect(() => {
if (!isEqual(argsProp, lastArgsProps.current)) {
getEmptyList();
lastArgsProps.current = argsProp as Args;
}
}, [argsProp, lastArgsProps]);
const getMore = async () => {
if (isLoadingRef.current || disabledMore) {
return;
}
try {
isLoadingRef.current = true;
const result = await getDataRequest({
...argsProp,
...getPaginationParams(data[data.length - 1]),
} as Args);
if (result.length > 0) {
setData((prev) => [...prev, ...result]);
} else {
setDisabledMore(true);
}
} catch (e) {
console.log(e);
}
isLoadingRef.current = false;
};
useLayoutEffect(() => {
const element = scrollElement.current;
if (isLoadingRef.current || !data.length) return;
if (element.scrollHeight - element.clientHeight <= 0) {
getMore().catch(console.log);
}
}, [data]);
const onScroll = useCallback(() => {
if (disabledMore || isLoadingRef.current) {
return;
}
const element = scrollElement.current;
const scrollPositionFromBottom = element.scrollHeight - (element.clientHeight + element.scrollTop);
if (scrollPositionFromBottom < SCROLL_POSITION_GAP) {
getMore().catch(console.log);
}
}, [disabledMore, getMore]);
useEffect(() => {
document.addEventListener('scroll', onScroll);
return () => {
document.removeEventListener('scroll', onScroll);
};
}, [onScroll]);
const isLoadingMore = data.length > 0 && isFetching;
return {
data,
isLoading: isLoading || (data.length === 0 && isFetching),
isLoadingMore,
refreshList: getEmptyList,
} as const;
};