Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function StatusMessage() {
- const HOOK_WINDOW_WIDTH = Symbol("window-width");
- const HOOK_NETWORK_STATUS = Symbol("network-status");
- const width = useWindowWidth(HOOK_WINDOW_WIDTH);
- const isOnline = useNetworkStatus(HOOK_NETWORK_STATUS);
- return (
- <>
- <p>Window width is {width}</p>
- <p>You are {isOnline ? 'online' : 'offline'}</p>
- </>
- );
- }
- function useSubscription(key, subscribe, unsubscribe, getValue) {
- const [state, setState] = useState(key, getValue()); // assumes a new useState(symbol, value) interface
- useEffect(() => {
- const handleChange = () => setState(key, getValue());
- subscribe(handleChange);
- return () => unsubscribe(handleChange);
- });
- return state;
- }
- function useWindowWidth(key) {
- const width = useSubscription(key,
- handler => window.addEventListener('resize', handler),
- handler => window.removeEventListener('resize', handler),
- () => window.innerWidth
- );
- return width;
- }
- function useNetworkStatus(key) {
- const isOnline = useSubscription(key,
- handler => {
- window.addEventListener('online', handler);
- window.addEventListener('offline', handler);
- },
- handler => {
- window.removeEventListener('online', handler);
- window.removeEventListener('offline', handler);
- },
- () => navigator.onLine
- );
- return isOnline;
- }
Add Comment
Please, Sign In to add comment