-1

I want to use const inside if(conditional branch), but I couldn't set const in if.

Is there a way to use const or set a variable in a conditional branch? Or are there any problems of my code?

Could you give some advice please?

export default class ApplauseButton extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      applause: 100,
      applauded: 0,
    };
  }

  handlClick= async ()=> {
      const {
        mainuser,
        subuser,
      } = this.props;

      if (mainuser === 'User1'){
        const countapplauded = this.state.applauded + 1;
      } else if (mainuser === 'User2') {
        const countapplauded1 = this.state.applauded1 + 1;
      }
  };

  render() {
    const {
      mainuser,
      subuser,
    } = this.props;

    return (
      <View style={styles.container}>
        <TouchableHighlight
          onPress={() => {this.handlClick()}}
          onLongPress={this._onLongPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>👋</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

4
  • 2
    Variables defined with const are block scoped, so they won't exist after the if/else blocks. What do you want to do with countapplauded and countapplauded1? You are not using them for anything. Commented Feb 14, 2019 at 15:06
  • 1
    stackoverflow.com/questions/38765194/… Have you seen this? Commented Feb 14, 2019 at 16:16
  • 1
    Or this: stackoverflow.com/questions/4174552/… Commented Feb 14, 2019 at 16:19
  • 1
    @Tholle Thank you for your comment! I din't understand variables exist only inside if/esle. Now, my code worked! Commented Feb 15, 2019 at 7:42

2 Answers 2

1

Maybe you like to use

if (mainuser === 'User1'){
   this.setState(prevState => {applauded: prevState.applauded + 1})
} else if (mainuser === 'User2') {
   this.setState(prevState => {applauded1: prevState.applauded1 + 1})
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this way:

const countapplauded= (mainuser==="User1"? this.state.applauded+ 1: this.state.applauded + 2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.