Skip to content

Instantly share code, notes, and snippets.

@absk1317
Created August 20, 2020 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save absk1317/d74a4f765530e38a66f14d54373efa67 to your computer and use it in GitHub Desktop.
Save absk1317/d74a4f765530e38a66f14d54373efa67 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import { connect } from 'react-redux';
import { setInternetStatus } from 'actions';
import { showToast } from '../utils/Library';
import PubSub from 'pubsub-js';
import { MESSAGE_TOPICS, Locales } from 'utils';
import { SemiBoldText } from 'components/common';
import { TextStyle, Row } from 'styles';
class NetworkInfo extends Component {
constructor(props) {
super(props);
this.state = { noInternet: false, weakInternet: false };
this.toggleLowNetworkStatus = this.toggleLowNetworkStatus.bind(this);
}
componentDidMount() {
this.lowNetworkSubscription = PubSub.subscribe(
MESSAGE_TOPICS.LOW_NETWORK,
this.toggleLowNetworkStatus
);
// Subscribe
this.unsubscribe = NetInfo.addEventListener(state => {
if (!state.isConnected || !state.isInternetReachable) {
if (!state.isConnected) showToast(Locales.pleaseConnectToInternet);
else if (!state.isInternetReachable) showToast(Locales.pleaseConnectToStableInternet);
this.setState({ noInternet: true });
this.props.setInternetStatus(true);
} else if (state.type == 'cellular' && state.details.cellularGeneration == '2g') {
showToast(Locales.youAreConnectedTo2G);
this.setState({ weakInternet: true });
} else {
this.props.setInternetStatus(false);
this.setState({ noInternet: false, weakInternet: false });
}
});
}
componentWillUnmount() {
PubSub.unsubscribe(this.lowNetworkSubscription);
this.unsubscribe();
}
toggleLowNetworkStatus(_key, params) {
this.setState({ weakInternet: params.weakInternet });
}
render() {
const { noInternet, weakInternet } = this.state;
const text = noInternet ? Locales.noInternet : Locales.poorInternetConnection;
if (weakInternet || noInternet) {
return (
<Row
style={{
flex: 0.05,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
height: 50,
}}
>
<Row style={{ alignItems: 'center' }}>
<SemiBoldText text={text} style={TextStyle.white14} />
<ActivityIndicator size="small" color="#fff" />
</Row>
</Row>
);
} else {
return null;
}
}
}
export default connect(
null,
{ setInternetStatus }
)(NetworkInfo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment