Search code examples
react-nativecomparison

How can I compare two variable in onPress?


I am trying to create a changing pin screen and i was failed in comparing two variable that getting from the user (new pin and comfirm pin). The error show me that "this.state.newpin" is an undefined object.

class SettingScreen extends Component {
  state = {
    oldpin: '000000',
    newpin: '',
    secpin: ''
}


  onPressButton(){
    if( this.state.newpin == this.state.secpin){
            ToastAndroid.show("Password Changed", ToastAndroid.SHORT);
            this.setState({ oldpin : this.state.newpin})
       }
       else {
            ToastAndroid.show("Password Unmatched", ToastAndroid.SHORT);
       }
    }

  handleNewPin = (text) => {
         this.setState({ newpin: text })
    }

  handleSecPin = (text) => {
         this.setState({ secpin: text })
     }

...

<TextInput onChangeText = {this.handleNewPin} />
<TextInput onChangeText = {this.handleSecPin} />

<TouchableOpacity onPress={this.onPressButton}>
    <Text> Change Password </Text>
</TouchableOpacity>

I can get the output for "this.state.newpin" and "this.state.secpin" from user. I just failed in the comparing statement ( OnPressButton()).

I am new in React-Native.

Sorry for any inconvenience.


Solution

  • you just need to bind your onPressButton()func. in the constructor with this. and move your state to constructor like this;

    class SettingScreen extends Component {
        constructor(props) {
            super(props);
            this.state = {
                oldpin: '000000',
                newpin: '',
                secpin: ''
            };
            this.onPressButton = this.onPressButton.bind(this);
        }
    }