forked from open-sauced/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetchTopContributors.ts
51 lines (42 loc) · 1.27 KB
/
useFetchTopContributors.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
import useSWR, { Fetcher } from "swr";
import { useState } from "react";
import { publicApiFetcher } from "lib/utils/public-api-fetcher";
type TopContributorsResponse = {
data: { login: string }[];
meta: Meta;
};
type TopContributorsOptions = {
limit?: number;
userId?: number;
};
const defaultOptions: TopContributorsOptions = {
limit: 10,
userId: undefined,
};
const useFetchTopContributors = (options: typeof defaultOptions) => {
const query = new URLSearchParams();
const { limit } = { ...defaultOptions, ...options };
const [page, setPage] = useState(1);
if (options.limit) {
query.set("limit", `${options.limit}`);
}
if (options.userId) {
query.set("userId", `${options.userId}`);
}
query.set("page", `${page}`);
const baseEndpoint = "users/top";
const endpointString = `${baseEndpoint}?${query}`;
const { data, error, mutate } = useSWR<TopContributorsResponse, Error>(
endpointString,
publicApiFetcher as Fetcher<TopContributorsResponse, Error>
);
return {
data: data?.data ?? [],
meta: data?.meta ?? { itemCount: 0, limit: 0, page: 0, hasNextPage: false, hasPreviousPage: false, pageCount: 0 },
isLoading: !error && !data,
isError: !!error,
setPage,
mutate,
};
};
export { useFetchTopContributors };