Created
February 19, 2024 19:56
-
-
Save Evavic44/8d613c729184572f86b486a0af95af85 to your computer and use it in GitHub Desktop.
State hook for detecting online status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Custom hook | |
import { useState, useEffect } from "react"; | |
export function useOnlineStatus() { | |
const [isOnline, setIsOnline] = useState<boolean>(true); | |
useEffect(() => { | |
function handleOnline() { | |
setIsOnline(true); | |
} | |
function handleOffline() { | |
setIsOnline(false); | |
} | |
window.addEventListener("online", () => handleOnline); | |
window.addEventListener("offline", () => handleOffline); | |
return () => { | |
window.removeEventListener("online", () => handleOnline); | |
window.removeEventListener("offline", () => handleOffline); | |
}; | |
}, []); | |
return isOnline; | |
} | |
// Statusbar component | |
"use client"; | |
import { useOnlineStatus } from "@/app/hooks/useOnlineStatus"; | |
export default function StatusBar() { | |
const online = useOnlineStatus(); | |
return ( | |
<div | |
className={`fixed top-0 left-0 z-50 flex item-center justify-center w-full text-center px-4 py-1 text-white ${ | |
online ? "bg-green-600" : "bg-red-500" | |
}`} | |
> | |
{online ? "Online ✅" : "Offline ❌"} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment