-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>
    );
  }
}

  • 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. – Tholle Feb 14 '19 at 15:06
  • 1
    https://stackoverflow.com/questions/38765194/conditionally-initializing-a-constant-in-javascript Have you seen this? – ageoff Feb 14 '19 at 16:16
  • 1
    Or this: https://stackoverflow.com/questions/4174552/can-global-constants-be-declared-in-javascript – Mukeyii Feb 14 '19 at 16:19
  • 1
    @Tholle Thank you for your comment! I din't understand variables exist only inside if/esle. Now, my code worked! –  Feb 15 '19 at 07:42

2 Answers2

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})
}
G.Elloumi
  • 24
  • 2
0

Try this way:

const countapplauded= (mainuser==="User1"? this.state.applauded+ 1: this.state.applauded + 2);
Harsha Vardhini
  • 692
  • 6
  • 10