Reputation: 651
I'm having problem changing state value in react native. When changing the value of (headerText). It doesn't change in the first call of the method. So it will be showing wrong output. Maybe because the value of (headerText) is based on (index) value which will be changing in the same time? How i can solve it? I need to assign an (index) value then assign (headerText) value
nextRiddle=()=>{
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
//next riddle
if(this.state.index < riddle.length-1){
this.setState({index : this.state.index+1})
this.setState({headerText : (this.state.index+1)});
} else {
this.setState({index : 0}) ;
}
//random color
randomIndexText = 0;
randomIndexButton = 0;
while(randomIndexText == randomIndexButton)
{
randomIndexText = Math.floor((Math.random() * (colorDark.length-1)));
randomIndexButton = Math.floor((Math.random() * (colorDark.length-1)));
}
this.setState({textBGColor : colorDark[randomIndexText]}) ;
this.setState({textColor : colorLight[randomIndexText]}) ;
this.setState({buttonBGColor : colorDark[randomIndexButton]}) ;
this.setState({buttonColor : colorLight[randomIndexButton]}) ;
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
this.setState({titleFont: 45});
//animation for riddle text
if(this.state.animationState==0){
this.state.textFont = 50
this.state.animationState =1;
}else{
this.state.textFont = 45
this.state.animationState =0;
}
}
Upvotes: 0
Views: 1588
Reputation: 8571
I suspect your issue is caused by the fact that setState
is async. You're writing the above code expecting that it's synchronous, which it's not.
In other words, this is what's happening:
this.setState({ foo: 'bar' });
this.state.foo; // undefined (or some other previous value).
And this is what you need to do instead (async):
this.setState({ foo: 'bar' }, () => {
this.state.foo; // 'bar', what we expect it to be.
});
You may have some general problems incorporating it into your existing code, but you need to tap into the second argument of setState
, which is the callback function.
Upvotes: 3