Reputation: 43
i am new in Reactjs my problem is that i have to detect the network status if wifi or internet connection is connected or disconnected
i tried using the below code but it wont detect network status correctly it always return false value
please help me
and here is my code and codesandbox.io
import React, { useEffect, useState } from 'react';
function App() {
const [status, setStatus] = useState(null)
useEffect(() => {
window.addEventListener('online', () => setStatus(navigator.onLine))
return () => window.removeEventListener('online', () => setStatus(navigator.onLine))
})
return (
<div>
<h2>Network Status Detector</h2>
{status ? <div style={{ top: 50, position: "absolute" }}>Network Connected</div> : <div style={{ top: 50, position: "absolute"}}>Network Disconnected</div>}
</div>
)
}
export default App;
Upvotes: 4
Views: 6280
Reputation: 1015
You need to use the same function reference for the event listener else it won't clean up on unmount/effect cleanup.
Here's a sample code for this
export default function App() {
return <NetworkStatus />;
}
const NetworkStatus = () => {
const [status, setStatus] = useState(true);
useEffect(() => {
function changeStatus() {
setStatus(navigator.onLine);
}
window.addEventListener("online", changeStatus);
window.addEventListener("offline", changeStatus);
return () => {
window.removeEventListener("online", changeStatus);
window.removeEventListener("offline", changeStatus);
};
}, []);
return status ? "Online" : "Offline";
};
Look how we're not using an arrow function here. We can either create the function inside the useEffect or a function returned by useCallback.
https://codesandbox.io/s/restless-cache-50wg5?file=/src/App.js
Upvotes: 4
Reputation: 578
There is an online and an offline event from the window object. You should be able to attach two listeners to the window like so:
useEffect(() => {
window.addEventListener('online', () => setStatus(true))
window.addEventListener('offline', () => setStatus(false))
}, [])
Upvotes: 3