I have a group of 4
TextInput
the first three set the value ok at 'onChange' method, but the last one is not getting set?
onChange(index : number, value : string) {
console.log(`onChange with index ${index} and val ${value}`);
switch (index) {
case 0:
console.log('capador 1');
this.setState({firstVal : value});
break;
case 1:
console.log('capador 2');
this.setState({secondVal : value});
break;
case 2:
console.log('capador 3');
this.setState({thirdVal : value});
break;
case 3:
console.log('capador 4');
this.setState({fourthVal : value});
break;
}
if (index === 3) {
console.log(`ya aya con input : ${this.state.firstVal}`);
console.log(`ya aya con input : ${this.state.secondVal}`);
console.log(`ya aya con input : ${this.state.thirdVal}`);
console.log(`ya aya con input : ${this.state.fourthVal}`); // why not setting?
}
}
So I can see in the console log, that the value is correct, but on the index === 3, the value is not returned.
this is the log:
onChange with index 0 and val 1
capador 1
onChange with index 1 and val 2
capador 2
onChange with index 2 and val 3
capador 3
onChange with index 3 and val 4
capador 4
ya aya con input : 1
ya aya con input : 2
ya aya con input : 3
ya aya con input :
And this is how the TextInputs looks like:
<TextInput
ref="third"
style={this.state.pos > 1 ? styles.textInputStyle : styles.textInputNormalStyle}
keyboardType = "number-pad"
maxLength={1}
onKeyPress={(event) => {this.onChange(2, event.nativeEvent.key); }}
/>
setState
does not immediately set the value, you have to wait for state update. You can check the value in setState
callback which is called when the state is updated. Consider the following snippet
this.setState({fourthVal : value}, () => {
console.log(`ya aya con input : ${this.state.firstVal}`);
console.log(`ya aya con input : ${this.state.secondVal}`);
console.log(`ya aya con input : ${this.state.thirdVal}`);
console.log(`ya aya con input : ${this.state.fourthVal}`);
});
Hope this will help!