Amrita Stha
Amrita Stha

Reputation: 3347

onPress is called automatically while using NetInfo - react native

NetInfo is used to check the connection & theres a checkNetwork function called in onPress of TouchableOpacity. When the button is clicked once, the checkNetwork function is called automatically multiple times without tapping the button when the network connection is lost and vice versa.

Please have a look at the code here:

Please have a look at the video

export default class App extends React.Component {

  checkNetwork = () => {
    NetInfo.addEventListener((state) => {
      if (state.isConnected) {
        alert('isConnected');
      } else {
        alert('not connected');
      }
    });
  };

  render() {
    return (
        <View style={styles.container}>
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={()=> this.checkNetwork()}>
                <Text>Check here</Text>
            </TouchableOpacity>
        </View>
    );
  }
}

Upvotes: 0

Views: 170

Answers (1)

Hagai Harari
Hagai Harari

Reputation: 2877

You should not declare event listener inside of the click itself,

export default class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {alert: ''};
  }
  componentDidMount() {
    NetInfo.addEventListener((state) =>  this.setState({ alert: state.isConnected ? 'isConnected' : 'not connected'})
 }
  checkNetwork = () => alert(this.state.alert)

  render() {
    return (
        <View style={styles.container}>
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={()=> this.checkNetwork()}>
                <Text>Check here</Text>
            </TouchableOpacity>
        </View>
    );
  }
}

though in your case event listener isn't exactly the fit logic for UI behavior of pressing button, so I think you might wanna use useNetInfo


import {useNetInfo} from "@react-native-community/netinfo";


class App extends React.Component {
 checkNetwork = () => {
      if (this.props.netInfo.isConnected) {
        alert('isConnected');
      } else {
        alert('not connected');
      }
    });
  };

...rest render...
}

export default () => <App netInfo={useNetInfo()} />

Upvotes: 1

Related Questions