import { useEffect, useState } from "react"; import { usePracticeAddressApi } from "../services/practiceAddressApi"; import { normalizeAddressLabel, type AddressCheck } from "../utils/practiceAddress"; const DEBOUNCE_MS = 300; // Checks the label as it is typed. Each answer is stored against the label it was for; the // caller compares that with the current value before trusting it. export const usePracticeAddressCheck = (value: string, enabled = true) => { const { checkAddress } = usePracticeAddressApi(); const label = normalizeAddressLabel(value); const [check, setCheck] = useState(); const [attempt, setAttempt] = useState(0); useEffect(() => { if (!enabled || !label) { setCheck(undefined); return; } let cancelled = false; setCheck({ label, state: "checking" }); const timer = setTimeout(() => { void checkAddress(label).then((state) => { if (!cancelled) setCheck({ label, state }); }); }, DEBOUNCE_MS); return () => { cancelled = true; clearTimeout(timer); }; }, [label, enabled, attempt, checkAddress]); return { check, retry: () => setAttempt((n) => n + 1) }; };