forked from open-sauced/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetchAllListContributors.ts
66 lines (56 loc) · 1.7 KB
/
useFetchAllListContributors.ts
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
import { useState } from "react";
import useSWR, { Fetcher, SWRConfiguration } from "swr";
import { publicApiFetcher } from "lib/utils/public-api-fetcher";
interface PaginatedResponse {
readonly data: DbListContributor[];
readonly meta: Meta;
}
type QueryObj = {
listId: string;
location?: string;
pr_velocity?: string;
timezone?: string;
initialLimit?: number;
contributor?: string;
};
const useFetchAllListContributors = (query: QueryObj, config?: SWRConfiguration, makeRequest = true) => {
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(query.initialLimit ?? 10);
const urlQuery = new URLSearchParams();
if (page) {
urlQuery.set("page", `${page}`);
}
if (query.location) {
urlQuery.set("location", `${query.location}`);
}
if (query.pr_velocity) {
urlQuery.set("pr_velocity", `${query.pr_velocity}`);
}
if (query.timezone) {
urlQuery.set("timezone", `${query.timezone}`);
}
if (query.contributor) {
urlQuery.set("contributor", `${query.contributor}`);
}
if (limit) {
urlQuery.set("limit", `${limit}`);
}
const baseEndpoint = `lists/${query.listId}/contributors`;
const endpointString = `${baseEndpoint}?${urlQuery}`;
const { data, error, mutate } = useSWR<PaginatedResponse, Error>(
makeRequest ? endpointString : null,
publicApiFetcher as Fetcher<PaginatedResponse, Error>,
config
);
return {
data: data?.data ?? [],
meta: data?.meta ?? { itemCount: 0, limit: 0, page: 0, hasNextPage: false, hasPreviousPage: false, pageCount: 0 },
isLoading: !error && !data && makeRequest,
isError: !!error,
mutate,
page,
setPage,
setLimit,
};
};
export default useFetchAllListContributors;