Skip to content

Commit 8fa178d

Browse files
authored
Merge pull request #268 from pzmudzinski/use-callback-function
fix useHttpsCallable causing infinite re-rendering
2 parents 866966d + c82aef0 commit 8fa178d

File tree

1 file changed

+34
-31
lines changed

1 file changed

+34
-31
lines changed

functions/useHttpsCallable.ts

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,20 @@ import {
33
httpsCallable,
44
HttpsCallableResult,
55
} from 'firebase/functions';
6-
import { useMemo, useState } from 'react';
6+
import { useState, useCallback } from 'react';
77

8-
export type HttpsCallableHook<RequestData = unknown, ResponseData = unknown> = [
9-
(
10-
data?: RequestData
11-
) => Promise<HttpsCallableResult<ResponseData> | undefined>,
12-
boolean,
13-
Error | undefined
14-
];
8+
export type HttpsCallableHook<
9+
RequestData = unknown,
10+
ResponseData = unknown
11+
> = Readonly<
12+
[
13+
(
14+
data?: RequestData
15+
) => Promise<HttpsCallableResult<ResponseData> | undefined>,
16+
boolean,
17+
Error | undefined
18+
]
19+
>;
1520

1621
export default <RequestData = unknown, ResponseData = unknown>(
1722
functions: Functions,
@@ -20,28 +25,26 @@ export default <RequestData = unknown, ResponseData = unknown>(
2025
const [error, setError] = useState<Error>();
2126
const [loading, setLoading] = useState<boolean>(false);
2227

23-
const callCallable = async (
24-
data?: RequestData
25-
): Promise<HttpsCallableResult<ResponseData> | undefined> => {
26-
const callable = httpsCallable<RequestData, ResponseData>(functions, name);
27-
setLoading(true);
28-
setError(undefined);
29-
try {
30-
return await callable(data);
31-
} catch (err) {
32-
setError(err as Error);
33-
} finally {
34-
setLoading(false);
35-
}
36-
};
37-
38-
const resArray: HttpsCallableHook<RequestData, ResponseData> = [
39-
callCallable,
40-
loading,
41-
error,
42-
];
43-
return useMemo<HttpsCallableHook<RequestData, ResponseData>>(
44-
() => resArray,
45-
resArray
28+
const callCallable = useCallback(
29+
async (
30+
data?: RequestData
31+
): Promise<HttpsCallableResult<ResponseData> | undefined> => {
32+
const callable = httpsCallable<RequestData, ResponseData>(
33+
functions,
34+
name
35+
);
36+
setLoading(true);
37+
setError(undefined);
38+
try {
39+
return await callable(data);
40+
} catch (err) {
41+
setError(err as Error);
42+
} finally {
43+
setLoading(false);
44+
}
45+
},
46+
[functions, name]
4647
);
48+
49+
return [callCallable, loading, error] as const;
4750
};

0 commit comments

Comments
 (0)