Skip to content

Commit d9b445e

Browse files
committed
[functions] Add useHttpsCallable hook
1 parent cca1573 commit d9b445e

File tree

8 files changed

+910
-208
lines changed

8 files changed

+910
-208
lines changed

auth/useAuthState.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export default (auth: Auth, options?: AuthStateOptions): AuthStateHook => {
1919
auth,
2020
async (user) => {
2121
if (options?.onUserChanged) {
22-
// onUserLoaded function to process custom claims on any other trigger function
22+
// onUserChanged function to process custom claims on any other trigger function
2323
try {
2424
await options.onUserChanged(user);
2525
} catch (e) {

firestore/types.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
DocumentData,
3-
DocumentReference,
43
DocumentSnapshot,
54
FirestoreError,
65
QuerySnapshot,

functions/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export {
2+
default as useHttpsCallable,
3+
HttpsCallableHook,
4+
} from './useHttpsCallable';

functions/package.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"name": "react-firebase-hooks/functions",
3+
"main": "dist/index.cjs.js",
4+
"module": "dist/index.esm.js",
5+
"typings": "dist/functions/index.d.ts"
6+
}

functions/useHttpsCallable.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { HttpsCallable, HttpsCallableResult } from 'firebase/functions';
2+
import { useMemo, useState } from 'react';
3+
4+
export type HttpsCallableHook<RequestData = unknown, ResponseData = unknown> = [
5+
(data?: RequestData) => Promise<HttpsCallableResult<ResponseData> | unknown>,
6+
boolean,
7+
Error | undefined
8+
];
9+
10+
export default <RequestData = unknown, ResponseData = unknown>(
11+
callable: HttpsCallable<RequestData, ResponseData>
12+
): HttpsCallableHook<RequestData, ResponseData> => {
13+
const [error, setError] = useState<Error>();
14+
const [loading, setLoading] = useState<boolean>(false);
15+
16+
const callCallable = async (
17+
data?: RequestData
18+
): Promise<HttpsCallableResult<ResponseData> | undefined> => {
19+
setLoading(true);
20+
try {
21+
return callable(data);
22+
} catch (err) {
23+
setError(err as Error);
24+
} finally {
25+
setLoading(false);
26+
}
27+
};
28+
29+
const resArray: HttpsCallableHook<RequestData, ResponseData> = [
30+
callCallable,
31+
loading,
32+
error,
33+
];
34+
return useMemo<HttpsCallableHook<RequestData, ResponseData>>(
35+
() => resArray,
36+
resArray
37+
);
38+
};

0 commit comments

Comments
 (0)