import { useEffect, useState } from "react"; import { useOrganizationServiceContext } from "../services/OrganizationService"; import { UNCHECKED, addressKey, confirmedZone, currentCheck, fromLookup, lookupAddressOf, type ZoneCheck, } from "../utils/locationTimeZoneCheck"; type AddressParts = { street?: string; city?: string; state?: string; postalCode?: string }; // Looks up the time zone whenever the address becomes complete or changes. Editing the address // clears any answer or correction; the new address is looked up afresh. export const useLocationTimeZone = (parts: AddressParts, enabled = true) => { const { lookupLocationTimeZone } = useOrganizationServiceContext(); const address = lookupAddressOf(parts); const key = enabled && address ? addressKey(address) : undefined; const [check, setCheck] = useState(UNCHECKED); const [attempt, setAttempt] = useState(0); useEffect(() => { if (!key || !address) { setCheck(UNCHECKED); return; } let cancelled = false; setCheck({ state: "checking", key }); // Waits for typing to settle so each keystroke is not a lookup. const timer = setTimeout(() => { lookupLocationTimeZone(address) .then((result) => { if (!cancelled) setCheck(fromLookup(key, result)); }) .catch(() => { if (!cancelled) setCheck({ state: "failed", key }); }); }, 400); return () => { cancelled = true; clearTimeout(timer); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, attempt, lookupLocationTimeZone]); const current = currentCheck(check, key); return { check: current, zone: confirmedZone(current), correct: (timeZone: string) => key && setCheck({ state: "corrected", key, timeZone }), retry: () => setAttempt((n) => n + 1), }; };