Guest User

Untitled

a guest
Dec 13th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. function StatusMessage() {
  2. const HOOK_WINDOW_WIDTH = Symbol("window-width");
  3. const HOOK_NETWORK_STATUS = Symbol("network-status");
  4.  
  5. const width = useWindowWidth(HOOK_WINDOW_WIDTH);
  6. const isOnline = useNetworkStatus(HOOK_NETWORK_STATUS);
  7. return (
  8. <>
  9. <p>Window width is {width}</p>
  10. <p>You are {isOnline ? 'online' : 'offline'}</p>
  11. </>
  12. );
  13. }
  14.  
  15. function useSubscription(key, subscribe, unsubscribe, getValue) {
  16. const [state, setState] = useState(key, getValue()); // assumes a new useState(symbol, value) interface
  17. useEffect(() => {
  18. const handleChange = () => setState(key, getValue());
  19. subscribe(handleChange);
  20. return () => unsubscribe(handleChange);
  21. });
  22. return state;
  23. }
  24.  
  25. function useWindowWidth(key) {
  26. const width = useSubscription(key,
  27. handler => window.addEventListener('resize', handler),
  28. handler => window.removeEventListener('resize', handler),
  29. () => window.innerWidth
  30. );
  31. return width;
  32. }
  33.  
  34. function useNetworkStatus(key) {
  35. const isOnline = useSubscription(key,
  36. handler => {
  37. window.addEventListener('online', handler);
  38. window.addEventListener('offline', handler);
  39. },
  40. handler => {
  41. window.removeEventListener('online', handler);
  42. window.removeEventListener('offline', handler);
  43. },
  44. () => navigator.onLine
  45. );
  46. return isOnline;
  47. }
Add Comment
Please, Sign In to add comment