Skip to content

Commit e18dbbe

Browse files
committed
Add an error state in use-two-factor-auth.ts
1 parent f779357 commit e18dbbe

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

resources/js/hooks/use-two-factor-auth.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ export const useTwoFactorAuth = () => {
2828
const [qrCodeSvg, setQrCodeSvg] = useState<string | null>(null);
2929
const [manualSetupKey, setManualSetupKey] = useState<string | null>(null);
3030
const [recoveryCodesList, setRecoveryCodesList] = useState<string[]>([]);
31+
const [errors, setErrors] = useState<{
32+
qrCode?: string;
33+
setupKey?: string;
34+
recoveryCodes?: string;
35+
}>({});
3136

3237
const hasSetupData = useMemo<boolean>(() => qrCodeSvg !== null && manualSetupKey !== null, [qrCodeSvg, manualSetupKey]);
3338

@@ -36,9 +41,8 @@ export const useTwoFactorAuth = () => {
3641
const { svg } = await fetchJson<TwoFactorSetupData>(qrCode.url());
3742

3843
setQrCodeSvg(svg);
39-
} catch (error) {
40-
console.error('Failed to fetch QR code:', error);
41-
44+
} catch {
45+
setErrors((prev) => ({ ...prev, qrCode: 'Failed to fetch QR code' }));
4246
setQrCodeSvg(null);
4347
}
4448
}, []);
@@ -48,36 +52,37 @@ export const useTwoFactorAuth = () => {
4852
const { secretKey: key } = await fetchJson<TwoFactorSecretKey>(secretKey.url());
4953

5054
setManualSetupKey(key);
51-
} catch (error) {
52-
console.error('Failed to fetch setup key:', error);
53-
55+
} catch {
56+
setErrors((prev) => ({ ...prev, setupKey: 'Failed to fetch a setup key' }));
5457
setManualSetupKey(null);
5558
}
5659
}, []);
5760

61+
const clearErrors = useCallback((): void => {
62+
setErrors({});
63+
}, []);
64+
5865
const clearSetupData = useCallback((): void => {
5966
setManualSetupKey(null);
6067
setQrCodeSvg(null);
61-
}, []);
68+
clearErrors();
69+
}, [clearErrors]);
6270

6371
const fetchRecoveryCodes = useCallback(async (): Promise<void> => {
6472
try {
6573
const codes = await fetchJson<string[]>(recoveryCodes.url());
6674

6775
setRecoveryCodesList(codes);
68-
} catch (error) {
69-
console.error('Failed to fetch recovery codes:', error);
70-
76+
} catch {
77+
setErrors((prev) => ({ ...prev, recoveryCodes: 'Failed to fetch recovery codes' }));
7178
setRecoveryCodesList([]);
7279
}
7380
}, []);
7481

7582
const fetchSetupData = useCallback(async (): Promise<void> => {
7683
try {
7784
await Promise.all([fetchQrCode(), fetchSetupKey()]);
78-
} catch (error) {
79-
console.error('Failed to fetch setup data:', error);
80-
85+
} catch {
8186
setQrCodeSvg(null);
8287
setManualSetupKey(null);
8388
}
@@ -88,6 +93,8 @@ export const useTwoFactorAuth = () => {
8893
manualSetupKey,
8994
recoveryCodesList,
9095
hasSetupData,
96+
errors,
97+
clearErrors,
9198
clearSetupData,
9299
fetchQrCode,
93100
fetchSetupKey,

0 commit comments

Comments
 (0)