Next.js Discord

Discord Forum

React documentation code doesn't function, it keeps saying "Online" even after disconn. internet.

Unanswered
KlaasPeters posted this in #help-forum
Open in Discord
Hi there, I was reading the documentation, learning about creating custom hooks. (See:https://react.dev/learn/reusing-logic-with-custom-hooks#custom-hooks-sharing-logic-between-components)
The problem is, is that the example code doesn't work on my pc, even if I copy paste the whole code, the connection keeps saying "Online" even after I disconnected the network, or enabled "Flight Mode". Does somebody know why the code isn't working for me? It should say "Disconnected" when I disconnect from the internet.

I was on the documentation page at this title: "Custom Hooks: Sharing logic between components", and this is a copy/paste from the code example that should work they say when I disconnect the internet, but it doesn't.

App.js:
import { useState, useEffect } from 'react';

export default function StatusBar() {
  const [isOnline, setIsOnline] = useState(true);
  useEffect(() => {
    function handleOnline() {
      setIsOnline(true);
    }
    function handleOffline() {
      setIsOnline(false);
    }
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return <h1>{isOnline ? '✅ Online' : '❌ Disconnected'}</h1>;
}

1 Reply

This is what happens, no internet and it keeps saying "Online", it should say "Disconnected".