Skip to content

Instantly share code, notes, and snippets.

@malte-wessel
Last active February 3, 2019 16:35
Show Gist options
  • Save malte-wessel/21bab2db933f9800471e88f96e4f957b to your computer and use it in GitHub Desktop.
Save malte-wessel/21bab2db933f9800471e88f96e4f957b to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'melody-hooks';
const getIsOffline =
typeof navigator.onLine === 'boolean'
? () => !navigator.onLine
: () => false;
export const useIsOffline = () => {
const [isOffline, setIsOffline] = useState(getIsOffline());
useEffect(() => {
const handleChange = () => setIsOffline(getIsOffline());
window.addEventListener('online', handleChange);
window.addEventListener('offline', handleChange);
return () => {
window.removeEventListener('online', handleChange);
window.removeEventListener('offline', handleChange);
};
}, []);
return isOffline;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment