UNPKG

react-storage-drafts

Version:

React Drafts is a library for creating, saving, and managing local documents in React applications.

30 lines (29 loc) 1.02 kB
import { useState, useEffect } from 'react'; import NetInfo from '@react-native-community/netinfo'; export default function useOnline({ enabled = true, }) { const [isOnline, setIsOnline] = useState(false); useEffect(() => { if (!enabled || typeof window === "undefined") { return; } const updateStatus = () => setIsOnline(navigator.onLine); window.addEventListener("online", updateStatus); window.addEventListener("offline", updateStatus); return () => { window.removeEventListener("online", updateStatus); window.removeEventListener("offline", updateStatus); }; }, [enabled]); useEffect(() => { if (!enabled || typeof window !== "undefined") { return; } const unsubscribe = NetInfo.addEventListener((state) => { setIsOnline(Boolean(state.isConnected)); }); return () => { unsubscribe(); }; }, [enabled]); return isOnline; }