-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.service.ts
42 lines (36 loc) · 1.08 KB
/
api.service.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
import React from "react";
import useSWR from "swr";
export type UseApiHook<I, O> = {
data: O|null,
error: any,
isLoading: boolean,
exec: (payload: I) => void
}
export const useApiPost = <I, O>(p: string, initialShouldFetch: boolean = false): UseApiHook<I, O> => {
const [shouldFetch, setShouldFetch] = React.useState(initialShouldFetch);
const [payload, setPayload] = React.useState<any>(null);
const defaultApiFetcher = (url: string, payload: I) => {
return fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
}).then(res => res.json());
}
const { data, error, isLoading } = useSWR(
shouldFetch ? [p, payload] : null,
() => defaultApiFetcher(p, payload),
{ revalidateOnFocus: false }
);
const exec = (newPayload: any) => {
setPayload(newPayload);
setShouldFetch(true);
};
return {
data,
error,
isLoading,
exec
} as UseApiHook<I, O>;
}