Skip to content

Instantly share code, notes, and snippets.

@Nedson202
Last active February 23, 2022 00:11
Show Gist options
  • Save Nedson202/9b2b1a4ee0fadea9b37927b68c1d74ce to your computer and use it in GitHub Desktop.
Save Nedson202/9b2b1a4ee0fadea9b37927b68c1d74ce to your computer and use it in GitHub Desktop.
Higher order component that watches for changes in network connection
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