-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathuseMapToAsyncPaginate.ts
More file actions
116 lines (98 loc) · 2.36 KB
/
useMapToAsyncPaginate.ts
File metadata and controls
116 lines (98 loc) · 2.36 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
import { useCallback, useMemo } from "react";
import type { GroupBase } from "react-select";
import { checkIsResponse } from "react-select-async-paginate";
import type {
LoadOptions,
UseAsyncPaginateParams,
} from "react-select-async-paginate";
import { get as defaultGet } from "./get";
import type { Additional, UseSelectFetchMapParams } from "./types";
export const errorText =
'[react-select-fetch] response should be an object with "options" prop, which contains array of options. Also you can use `mapResponse` param';
export const defaultResponseMapper = <
OptionType,
Group extends GroupBase<OptionType>,
>(
response: unknown,
) => {
if (checkIsResponse<OptionType, Group, Additional>(response)) {
return response;
}
throw new Error(errorText);
};
export const useMapToAsyncPaginate = <
OptionType,
Group extends GroupBase<OptionType>,
>(
selectFetchParams: UseSelectFetchMapParams<OptionType, Group>,
): UseAsyncPaginateParams<OptionType, Group, Additional> => {
const {
url,
queryParams = {},
searchParamName = "search",
pageParamName = "page",
offsetParamName = "offset",
mapResponse = defaultResponseMapper,
get = defaultGet,
initialPage = 1,
defaultInitialPage = 2,
} = selectFetchParams;
const additional = useMemo<Additional>(
() => ({
page: initialPage,
}),
[initialPage],
);
const defaultAdditional = useMemo<Additional>(
() => ({
page: defaultInitialPage,
}),
[defaultInitialPage],
);
const loadOptions = useCallback<LoadOptions<OptionType, Group, Additional>>(
async (search, prevOptions, currentAdditional) => {
if (currentAdditional === undefined) {
throw new Error();
}
const { page } = currentAdditional;
const params: Record<string, unknown> = {
...queryParams,
};
if (searchParamName) {
params[searchParamName] = search;
}
if (pageParamName) {
params[pageParamName] = page;
}
if (offsetParamName) {
params[offsetParamName] = prevOptions.length;
}
const result = await get(url, params);
const response = mapResponse(result, {
search,
prevPage: page,
prevOptions,
});
return {
...response,
additional: {
page: page + 1,
},
};
},
[
url,
queryParams,
searchParamName,
pageParamName,
offsetParamName,
mapResponse,
get,
],
);
return {
loadOptions,
additional,
defaultAdditional,
};
};