From f46a2d68a004239bb991871a33f10b49320f0e3b Mon Sep 17 00:00:00 2001 From: shamsmosowi Date: Sat, 10 Jun 2023 18:20:34 +0200 Subject: [PATCH] fix offline indicator --- src/components/TableToolbar/LoadedRowsStatus.tsx | 16 +++++++++------- src/hooks/useOffline.ts | 16 +++++++++++++++- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/components/TableToolbar/LoadedRowsStatus.tsx b/src/components/TableToolbar/LoadedRowsStatus.tsx index cf0499bec..f216e80f1 100644 --- a/src/components/TableToolbar/LoadedRowsStatus.tsx +++ b/src/components/TableToolbar/LoadedRowsStatus.tsx @@ -12,6 +12,7 @@ import { serverDocCountAtom, } from "@src/atoms/tableScope"; import { spreadSx } from "@src/utils/ui"; +import useOffline from "@src/hooks/useOffline"; const StatusText = forwardRef(function StatusText( props: TypographyProps, @@ -77,13 +78,8 @@ function LoadedRowsStatus() { } export default function SuspendedLoadedRowsStatus() { - if (navigator.onLine) { - return ( - {loadingIcon}Loading…}> - - - ); - } else { + const isOffline = useOffline(); + if (isOffline) { return ( @@ -92,5 +88,11 @@ export default function SuspendedLoadedRowsStatus() { ); + } else { + return ( + {loadingIcon}Loading…}> + + + ); } } diff --git a/src/hooks/useOffline.ts b/src/hooks/useOffline.ts index ad5cb1995..5dd9ffd5a 100644 --- a/src/hooks/useOffline.ts +++ b/src/hooks/useOffline.ts @@ -5,10 +5,24 @@ export default function useOffline() { const handleOffline = () => setIsOffline(true); const handleOnline = () => setIsOffline(false); + const checkOnlineStatus = async () => { + try { + const res = await fetch("https://httpbin.org/get", { cache: "no-store" }); + if (res.status >= 200 && res.status < 300) { + handleOnline(); + } else { + handleOffline(); + } + } catch (error) { + handleOffline(); + } + }; useEffect(() => { // Need to set here because the listener doesn’t fire on initial load setIsOffline(!window.navigator.onLine); - + if (!window.navigator.onLine) { + checkOnlineStatus(); + } window.addEventListener("offline", handleOffline); window.addEventListener("online", handleOnline);