Kakar Kakar - 3 months ago 22
React JSX Question

React native picker and console showing different value of the same state

I would like to use a picker to select countries:

export default class RegisterMobile extends Component {
constructor(props) {
super(props)
this.state = {
country: 'india',
}
}

changeCountry = (c) => {
this.setState({
country: c,
})
console.log(this.state.country);
}

render() {
return(
<View style={styles.container}>
<View style={styles.selectCountry}>
<Picker selectedValue={this.state.country} onValueChange={this.changeCountry}>
<Picker.Item label="India" value="india" />
<Picker.Item label="China" value="china" />
</Picker>
</View>
</View>
)
}
}



  • In the emulator:

    At first the Label is India. When I select from India to China, the Label is changed to China. Again if I pick India, the label is changed to India.

  • However, in the console:

    At first
    this.state.country
    is india. But when I select from India to China, nothing is changed, except that india is twice. Again if I select from china to india,
    this.state.country
    is china instead of india.



What am I doing wrong here? I really can't figure it out. This should have been working because in the emulator if I select china/india, the label changes accordingly. What am I missing here? Please help me. Thank you.

Answer

this.setState call is not a synchronous process. calling setState put it an update batch. Your console.log statement should be called in callback argument of setState:

this.setState({country: c,},
         ()=>{ console.log(this.state.country)}
 )

See setState doc