Skip to content

Instantly share code, notes, and snippets.

@Evavic44
Created February 19, 2024 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Evavic44/8d613c729184572f86b486a0af95af85 to your computer and use it in GitHub Desktop.
Save Evavic44/8d613c729184572f86b486a0af95af85 to your computer and use it in GitHub Desktop.
State hook for detecting online status
// 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