Skip to content

Commit

Permalink
fix offline indicator
Browse files Browse the repository at this point in the history
  • Loading branch information
shamsmosowi committed Jun 10, 2023
1 parent 48a786c commit f46a2d6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
16 changes: 9 additions & 7 deletions src/components/TableToolbar/LoadedRowsStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -77,13 +78,8 @@ function LoadedRowsStatus() {
}

export default function SuspendedLoadedRowsStatus() {
if (navigator.onLine) {
return (
<Suspense fallback={<StatusText>{loadingIcon}Loading…</StatusText>}>
<LoadedRowsStatus />
</Suspense>
);
} else {
const isOffline = useOffline();
if (isOffline) {
return (
<Tooltip title="Changes will be saved when you reconnect" describeChild>
<StatusText color="error.main">
Expand All @@ -92,5 +88,11 @@ export default function SuspendedLoadedRowsStatus() {
</StatusText>
</Tooltip>
);
} else {
return (
<Suspense fallback={<StatusText>{loadingIcon}Loading…</StatusText>}>
<LoadedRowsStatus />
</Suspense>
);
}
}
16 changes: 15 additions & 1 deletion src/hooks/useOffline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit f46a2d6

Please sign in to comment.