I am trying to write an util function that checks if the user is connected to internet or not, not when connected to a network.
I used this below but it only work when user is connected to a network, if I turn off the internet of the network it would still be connected because the navigator.onLine
works on a network:
"use client";
import React, { useState, useEffect } from "react";
export const OfflineDetector = () => {
const [isOnline, setIsOnline] = useState(false);
useEffect(() => {
setIsOnline(navigator?.onLine);
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return (
<div>
{!isOnline && (
<p className="bg-red-500 text-center text-white">
You are currently offline. Please check your internet connection.
</p>
)}
</div>
);
};
So I have tried to make a fetch to a reliable url but it’s not working as expected:
"use client";
import React, { useState, useEffect } from "react";
export const OfflineDetector = () => {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
const checkInternetConnection = async () => {
try {
const response = await fetch("https://www.google.com/favicon.ico", {
method: "HEAD",
cache: "no-cache",
});
if (response.ok) {
setIsOnline(true);
} else {
setIsOnline(false);
}
} catch (error) {
setIsOnline(false);
}
};
const handleOnline = () => {
checkInternetConnection();
};
const handleOffline = () => {
setIsOnline(false);
};
// Initial check
checkInternetConnection();
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return (
<div>
{!isOnline && (
<p className="bg-red-500 text-center text-white">
You are currently offline. Please check your internet connection.
</p>
)}
</div>
);
};