From d6a1aa362bf59a9c440268d029e6637d703972e0 Mon Sep 17 00:00:00 2001 From: Blazing-mike Date: Wed, 6 Mar 2024 13:49:43 +0100 Subject: [PATCH] change useOfflineCheck to use online and offline events --- packages/webapp/src/hooks/useOfflineCheck.ts | 62 ++++++-------------- 1 file changed, 17 insertions(+), 45 deletions(-) diff --git a/packages/webapp/src/hooks/useOfflineCheck.ts b/packages/webapp/src/hooks/useOfflineCheck.ts index 646e30d8..e7f15532 100644 --- a/packages/webapp/src/hooks/useOfflineCheck.ts +++ b/packages/webapp/src/hooks/useOfflineCheck.ts @@ -1,60 +1,32 @@ import { useState, useEffect } from "react"; import { toast } from "sonner"; -async function performNetworkCheck() { - const endpoint = "https://www.google.com"; - const response = await fetch(endpoint, { - method: "HEAD", - cache: "no-cache", - mode: "no-cors", - }); - return response.ok; -} - -function useOfflineCheck(options: any = {}) { - const { - - maxRetries = 3, // Maximum number of retries before assuming offline - retryDelay = 1500, // Delay between retries (ms) - } = options; - - const [retries, setRetries] = useState(0); - +function useOfflineCheck() { + const [isOnline, setIsOnline] = useState(true); useEffect(() => { - const handleOffline = () => { - if (retries < maxRetries) { - setTimeout(() => { - performNetworkCheck() - .then(() => { - setRetries(0); - toast.dismiss(); - }) // online - .catch(() => { - const newRetry = retries + 1; - setRetries(newRetry); // Retry if error occurs - }); - }, retryDelay); - } - }; + const handleOnline = () => setIsOnline(true); + const handleOffline = () => setIsOnline(false); - window.addEventListener("online", handleOffline); + window.addEventListener("online", handleOnline); window.addEventListener("offline", handleOffline); - // Initial network check: - performNetworkCheck() - .then(() => { - setRetries(0); - }) - .catch(() => { - toast.error("App is offline. Please check your internet connection.",{ dismissible: false, duration: Infinity }); - }); - return () => { + window.removeEventListener("online", handleOnline); window.removeEventListener("offline", handleOffline); }; - }, [ maxRetries, retryDelay, retries]); + }, []); + useEffect(() => { + if (!isOnline) { + toast.error("App is offline. Please check your internet connection.", { + dismissible: false, + duration: Infinity, + }); + } else { + toast.dismiss(); + } + }, [isOnline]); } export default useOfflineCheck;