Reputation: 27
class Search extends React.Component {
constructor(props){
super(props);
this.state = {count : 0}
this.M = {Message : " "}
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.result = this.result.bind(this);
this.result();
}
increment(){
this.setState({count : this.state.count + 1}) ;
this.result()
this.forceUpdate();
}
decrement() {
this.setState({count : this.state.count - 1});
this.result()
this.forceUpdate();
}
result() {
if (this.state.count >0)
{
this.forceUpdate();
// this.setState({Message : "positive"});
this.M.Message = "Positive";
// this.forceUpdate();
} else
{
this.M.Message = "Negative";
// this.forceUpdate();
// this.setState({Message : "NEGATIVE "});
}
this.forceUpdate();
}
// }
render() {
return (
<View>
<Text style = {{margin: 45, fontSize: 22}}>you have {this.state.count} Coin</Text>
<Button
onPress={this.increment}
title="win Coin "
color="#841584" />
<Button
onPress = {this.decrement}
title="lose Coin"
color="#841584" />
<Text style = {{fontSize : 28}}> Result : {this.M.Message} </Text>
</View>
)
}
}
**the bug is when the count equal 0 or -1 it has the result of the prevents exemple one the user click on lose Coin the result is -1 so the message is "negative" but when he click another time on the button win coin the result get 0 and the result is not Positive but Negative the precedent result and just for the two result is 0 and -1 **
Upvotes: 1
Views: 4073
Reputation: 429
I found out the source of the problem. As you may know, this.setState() is asynchronous. You can achieve the result you want by simply changing the setState to this
increment() {
this.setState({ count: this.state.count + 1 }, () => {
this.result();
this.forceUpdate();
});
}
Make sure you also change 'decrement' too.
Upvotes: 1