(versionId: string | undefined)
| 5 | export type ExternalAuthPollingState = "idle" | "polling" | "abandoned"; |
| 6 | |
| 7 | export const useExternalAuth = (versionId: string | undefined) => { |
| 8 | const [pollingState, setPollingState] = useState< |
| 9 | Record<string, ExternalAuthPollingState> |
| 10 | >({}); |
| 11 | |
| 12 | const startPollingExternalAuth = useCallback((providerId: string) => { |
| 13 | setPollingState((prev) => ({ ...prev, [providerId]: "polling" })); |
| 14 | }, []); |
| 15 | |
| 16 | const isAnyPolling = Object.values(pollingState).some((s) => s === "polling"); |
| 17 | |
| 18 | const { |
| 19 | data: externalAuth, |
| 20 | isPending: isLoadingExternalAuth, |
| 21 | error, |
| 22 | } = useQuery({ |
| 23 | ...templateVersionExternalAuth(versionId ?? ""), |
| 24 | enabled: Boolean(versionId), |
| 25 | refetchInterval: isAnyPolling ? 1000 : false, |
| 26 | }); |
| 27 | |
| 28 | // Stop polling individual providers once they authenticate. |
| 29 | useEffect(() => { |
| 30 | if (!externalAuth) { |
| 31 | return; |
| 32 | } |
| 33 | setPollingState((prev) => { |
| 34 | let changed = false; |
| 35 | const next = { ...prev }; |
| 36 | for (const auth of externalAuth) { |
| 37 | if (auth.authenticated && next[auth.id] === "polling") { |
| 38 | next[auth.id] = "idle"; |
| 39 | changed = true; |
| 40 | } |
| 41 | } |
| 42 | return changed ? next : prev; |
| 43 | }); |
| 44 | }, [externalAuth]); |
| 45 | |
| 46 | // Per-provider 60-second timeout. |
| 47 | useEffect(() => { |
| 48 | const pollingIds = Object.entries(pollingState) |
| 49 | .filter(([, authPollingState]) => authPollingState === "polling") |
| 50 | .map(([id]) => id); |
| 51 | |
| 52 | if (pollingIds.length === 0) { |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | const timers = pollingIds.map((id) => |
| 57 | setTimeout(() => { |
| 58 | setPollingState((prev) => |
| 59 | prev[id] === "polling" ? { ...prev, [id]: "abandoned" } : prev, |
| 60 | ); |
| 61 | }, 60_000), |
| 62 | ); |
| 63 | |
| 64 | return () => { |
no test coverage detected