/
useIssues.ts
45 lines (39 loc) · 1.22 KB
/
useIssues.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
import { useCallback, useEffect, useState } from "react";
import { Issue, IssuesResponse } from "@/pages/api/issues";
export const useIssues = () => {
const [loading, setLoading] = useState(true);
const [repositoryId, setRepositoryId] = useState<string | undefined>();
const [issues, setIssues] = useState<Issue[]>([]);
const getIssues = useCallback(async (): Promise<IssuesResponse> => {
const res = await fetch("/api/issues");
return await res.json();
}, []);
const createIssue = useCallback(
async (title: string, body?: string) => {
const res = await fetch("/api/issues", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
repositoryId,
title,
body,
}),
});
const newIssue: Issue = await res.json();
setIssues([newIssue, ...issues]);
},
[repositoryId, issues]
);
useEffect(() => {
(async () => {
const res = await getIssues();
setRepositoryId(res.repository.id);
setIssues(res.repository.issues.nodes);
setLoading(false);
})();
}, [getIssues]);
return { issues, createIssue, loading };
};