Need to use the event listener for this: window.addEventListener('online', () => { ...});
.
Inside the callback for listener, do setState
to check online off-line toggle.
here is small hook
i created in reactjs
to handle online offline states:
import { useEffect, useState } from 'react';
// toastr alert messages
import { showOffline, showOnline } from 'utils/alerts';
const useNetworkStatus = () => {
const [state, setState] = useState(true);
async function isOnline() {
// if its offline and to check if window?.navigator is supported.
if (!window?.navigator?.onLine) {
setState(false);
return false;
}
// Failover case:
// navigator.onLine cannot be trusted: there's situation where you appear to be online (connect to a network with no internet)
// but still cannot access the internet.
// So to fix: we request to our own origin to avoid CORS errors
const url = new URL(window.location.origin);
// with random value to prevent cached responses
url.searchParams.set('rand', Date.now());
try {
const response = await fetch(url.toString(), { method: 'HEAD' });
setState(true);
return response.ok;
} catch {
setState(false);
return false;
}
}
useEffect(() => {
const setOnlineOnVisibleChange = async () => {
// if its page is visible and state was offline
if (!document?.hidden && !state) {
if (await isOnline()) showOnline();
}
};
// on visiting the page again if the state is offline and network is online, then show online alert
if ('hidden' in document)
document.addEventListener('visibilitychange', setOnlineOnVisibleChange, false);
return () => document.removeEventListener('visibilitychange', setOnlineOnVisibleChange, false);
}, [state]);
useEffect(() => {
async function changeStatus() {
if (await isOnline()) showOnline();
else showOffline();
}
// Listen for the page to be finished loading
window.addEventListener('load', () => {
// if its offline
if (!isOnline()) showOffline();
});
window.addEventListener('online', changeStatus);
window.addEventListener('offline', changeStatus);
return () => {
window.removeEventListener('online', changeStatus);
window.removeEventListener('offline', changeStatus);
};
}, []);
};
export default useNetworkStatus;