@hooks/network-status
Version:
React hook return network status details
25 lines (24 loc) • 1.11 kB
JavaScript
import { useState, useEffect } from 'react';
const ONLINE = 'online';
const OFFLINE = 'offline';
export default function useNetworkStatus() {
var _a;
const [status, setStatus] = useState({
online: typeof window !== 'undefined' ? (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.onLine : undefined,
});
useEffect(() => {
const updateOnlineStatus = () => {
setStatus(prevStatus => {
var _a;
return (Object.assign(Object.assign({}, prevStatus), { online: typeof window !== 'undefined' ? (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.onLine : undefined }));
});
};
window.addEventListener(ONLINE, updateOnlineStatus);
window.addEventListener(OFFLINE, updateOnlineStatus);
return () => {
window.removeEventListener(ONLINE, updateOnlineStatus);
window.removeEventListener(OFFLINE, updateOnlineStatus);
};
}, []);
return status;
}