|
1 | | -import { isReverificationCancelledError } from '@clerk/shared/error'; |
2 | | -import { useRef, useState } from 'react'; |
3 | | - |
4 | | -import type { ErrorDescription } from '../../../localization'; |
5 | | -import { useErrorText } from '../../../localization'; |
6 | | -import { toLocalizableError } from '../../../utils/errors'; |
| 1 | +import { usePendingAction } from '../../../hooks/use-pending-action'; |
7 | 2 | import type { ReverificationController } from '../../reverification'; |
| 3 | +import { REDIRECT_HOLD_MS } from '../user-profile.utils'; |
8 | 4 | import type { |
9 | 5 | EnterpriseAccountActionResult, |
10 | 6 | UserProfileEnterpriseAccount, |
@@ -34,42 +30,20 @@ export function useUserProfileEnterpriseAccountsController({ |
34 | 30 | connectReverification, |
35 | 31 | errorFallback, |
36 | 32 | }: UserProfileEnterpriseAccountsControllerOptions): UserProfileEnterpriseAccountsController { |
37 | | - const [pendingId, setPendingId] = useState<string>(); |
38 | | - const errorText = useErrorText(); |
39 | | - const [connectErrors, setConnectErrors] = useState<Record<string, ErrorDescription>>({}); |
40 | | - const connecting = useRef(false); |
41 | | - |
42 | | - const run = async (id: string) => { |
43 | | - if (connecting.current) { |
44 | | - return; |
45 | | - } |
46 | | - connecting.current = true; |
47 | | - setPendingId(id); |
48 | | - setConnectErrors(({ [id]: _cleared, ...rest }) => rest); |
49 | | - |
50 | | - try { |
51 | | - if ((await onConnect(id)) === 'redirecting') { |
52 | | - await new Promise(resolve => setTimeout(resolve, 2000)); |
53 | | - } |
54 | | - } catch (error) { |
55 | | - if (isReverificationCancelledError(error)) { |
56 | | - return; |
57 | | - } |
58 | | - setConnectErrors(current => ({ ...current, [id]: toLocalizableError(error) })); |
59 | | - } finally { |
60 | | - connecting.current = false; |
61 | | - setPendingId(undefined); |
62 | | - } |
63 | | - }; |
| 33 | + const actions = usePendingAction({ errorFallback }); |
64 | 34 |
|
65 | 35 | return { |
66 | 36 | accounts, |
67 | | - connections: connections.map(connection => { |
68 | | - const error = connectErrors[connection.id]; |
69 | | - return error ? { ...connection, connectError: errorText(error, errorFallback) } : connection; |
70 | | - }), |
71 | | - pendingId, |
72 | | - onConnect: id => void run(id), |
| 37 | + connections: connections.map(connection => |
| 38 | + actions.errorKey === connection.id ? { ...connection, connectError: actions.error } : connection, |
| 39 | + ), |
| 40 | + pendingId: actions.pendingKey, |
| 41 | + onConnect: id => |
| 42 | + void actions.run(id, async () => { |
| 43 | + if ((await onConnect(id)) === 'redirecting') { |
| 44 | + await new Promise(resolve => setTimeout(resolve, REDIRECT_HOLD_MS)); |
| 45 | + } |
| 46 | + }), |
73 | 47 | connectReverification, |
74 | 48 | }; |
75 | 49 | } |
0 commit comments