Last active
February 23, 2022 00:11
-
-
Save Nedson202/9b2b1a4ee0fadea9b37927b68c1d74ce to your computer and use it in GitHub Desktop.
Higher order component that watches for changes in network connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
export default function (ComposedComponent) { | |
class NetworkDetector extends Component { | |
state = { | |
isDisconnected: false | |
} | |
componentDidMount() { | |
this.handleConnectionChange(); | |
window.addEventListener('online', this.handleConnectionChange); | |
window.addEventListener('offline', this.handleConnectionChange); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('online', this.handleConnectionChange); | |
window.removeEventListener('offline', this.handleConnectionChange); | |
} | |
handleConnectionChange = () => { | |
const condition = navigator.onLine ? 'online' : 'offline'; | |
if (condition === 'online') { | |
const webPing = setInterval( | |
() => { | |
fetch('//google.com', { | |
mode: 'no-cors', | |
}) | |
.then(() => { | |
this.setState({ isDisconnected: false }, () => { | |
return clearInterval(webPing) | |
}); | |
}).catch(() => this.setState({ isDisconnected: true }) ) | |
}, 2000); | |
return; | |
} | |
return this.setState({ isDisconnected: true }); | |
} | |
render() { | |
const { isDisconnected } = this.state; | |
return ( | |
<div> | |
{ isDisconnected && (<div className="internet-error"> | |
<p>Internet connection lost</p> | |
</div>) | |
} | |
<ComposedComponent {...this.props} /> | |
</div> | |
); | |
} | |
} | |
return NetworkDetector; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment