From 0edd8cf015fea5dcf4642f6b1dc2bb93f30ce144 Mon Sep 17 00:00:00 2001 From: Allan Joston Fernandes <54631653+Allan2000-Git@users.noreply.github.com> Date: Sat, 14 Dec 2024 13:02:01 +0530 Subject: [PATCH] feat(platofrm): Added online/offline status detection in the platform (#585) --- apps/platform/src/app/layout.tsx | 6 +++- .../common/online-status-handler.tsx | 10 ++++++ apps/platform/src/hooks/use-online-status.ts | 33 +++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 apps/platform/src/components/common/online-status-handler.tsx create mode 100644 apps/platform/src/hooks/use-online-status.ts diff --git a/apps/platform/src/app/layout.tsx b/apps/platform/src/app/layout.tsx index d9e2a617..011b6b19 100644 --- a/apps/platform/src/app/layout.tsx +++ b/apps/platform/src/app/layout.tsx @@ -1,6 +1,7 @@ import { Toaster } from '@/components/ui/sonner' import './global.css' import JotaiProvider from '@/components/jotaiProvider' +import OnlineStatusHandler from '@/components/common/online-status-handler' export const metadata = { title: 'Keyshade', @@ -15,7 +16,10 @@ export default function RootLayout({ return ( - {children} + + + {children} + diff --git a/apps/platform/src/components/common/online-status-handler.tsx b/apps/platform/src/components/common/online-status-handler.tsx new file mode 100644 index 00000000..f5685750 --- /dev/null +++ b/apps/platform/src/components/common/online-status-handler.tsx @@ -0,0 +1,10 @@ +'use client' + +import { useOnlineStatus } from "@/hooks/use-online-status"; + +function OnlineStatusHandler() { + useOnlineStatus(); + return null; +} + +export default OnlineStatusHandler; diff --git a/apps/platform/src/hooks/use-online-status.ts b/apps/platform/src/hooks/use-online-status.ts new file mode 100644 index 00000000..e6758e1f --- /dev/null +++ b/apps/platform/src/hooks/use-online-status.ts @@ -0,0 +1,33 @@ +import { useEffect, useRef } from "react" +import { toast } from "sonner"; + +export const useOnlineStatus = () => { + const statusTimeout = useRef(null); + + const statusHandler = () => { + if (statusTimeout.current) { + clearTimeout(statusTimeout.current); + } + + statusTimeout.current = setTimeout(() => { + if (navigator.onLine) { + toast.success("You are back online! Refreshing..."); + setTimeout(() => { + window.location.reload(); + }, 1000); + } else { + toast.error("You are offline"); + } + }, 1000); + }; + + useEffect(() => { + window.addEventListener("online", statusHandler); + window.addEventListener("offline", statusHandler); + + return () => { + window.removeEventListener("online", statusHandler); + window.removeEventListener("offline", statusHandler); + } + }, []); +} \ No newline at end of file