diff --git a/src/browser/modules/Main/main.hooks.tsx b/src/browser/modules/Main/main.hooks.tsx index 9c57e8a927a..cffc3c66c18 100644 --- a/src/browser/modules/Main/main.hooks.tsx +++ b/src/browser/modules/Main/main.hooks.tsx @@ -26,54 +26,50 @@ import { CONNECTING_STATE } from 'shared/modules/connections/connectionsDuck' -/** - * Custom hook for detecting slow connections - * @param {object} props - * @param {number} props.connectionState - * @param {string} props.errorMessage - * @param {number} props.lastConnectionUpdate - * @return {boolean[]} - */ +const FIVE_SECONDS = 5 * 1000 +const TEN_SECONDS = 10 * 1000 + export function useSlowConnectionState({ connectionState, errorMessage, lastConnectionUpdate -}: any) { +}: { + connectionState: number + errorMessage?: string + lastConnectionUpdate: number +}): [boolean, boolean] { const [past5Sec, setPast5Sec] = useState(false) const [past10Sec, setPast10Sec] = useState(false) - const DELAY_5SEC = 5 * 1000 // five seconds - const DELAY_10SEC = 10 * 1000 // ten seconds - const shouldTimeConnection = () => - [CONNECTING_STATE, PENDING_STATE].includes(connectionState) && !errorMessage - let timeout5Sec: any = null - let timeout10Sec: any = null useEffect(() => { - if (!shouldTimeConnection()) { - clearTimeout(timeout5Sec) - clearTimeout(timeout10Sec) + const shouldTimeConnection = + [CONNECTING_STATE, PENDING_STATE].includes(connectionState) && + !errorMessage + + if (!shouldTimeConnection) { setPast5Sec(false) setPast10Sec(false) return } - timeout5Sec = setTimeout(() => { + const timeout5Sec = setTimeout(() => { const diff = Date.now() - lastConnectionUpdate - setPast5Sec(diff > DELAY_5SEC) - }, DELAY_5SEC) - timeout10Sec = setTimeout(() => { + setPast5Sec(diff > FIVE_SECONDS) + }, FIVE_SECONDS) + + const timeout10Sec = setTimeout(() => { const diff = Date.now() - lastConnectionUpdate - setPast10Sec(diff > DELAY_10SEC) - }, DELAY_10SEC) + setPast10Sec(diff > TEN_SECONDS) + }, TEN_SECONDS) return () => { clearTimeout(timeout5Sec) clearTimeout(timeout10Sec) } - }, [connectionState, lastConnectionUpdate]) + }, [connectionState, lastConnectionUpdate, errorMessage]) return [past5Sec, past10Sec] }