-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathuseHttpsCallable.ts
50 lines (46 loc) · 1.15 KB
/
useHttpsCallable.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
import {
Functions,
httpsCallable,
HttpsCallableResult,
} from 'firebase/functions';
import { useCallback, useState } from 'react';
export type HttpsCallableHook<
RequestData = unknown,
ResponseData = unknown
> = Readonly<
[
(
data?: RequestData
) => Promise<HttpsCallableResult<ResponseData> | undefined>,
boolean,
Error | undefined
]
>;
export default <RequestData = unknown, ResponseData = unknown>(
functions: Functions,
name: string
): HttpsCallableHook<RequestData, ResponseData> => {
const [error, setError] = useState<Error>();
const [loading, setLoading] = useState<boolean>(false);
const callCallable = useCallback(
async (
data?: RequestData
): Promise<HttpsCallableResult<ResponseData> | undefined> => {
const callable = httpsCallable<RequestData, ResponseData>(
functions,
name
);
setLoading(true);
setError(undefined);
try {
return await callable(data);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
},
[functions, name]
);
return [callCallable, loading, error] as const;
};