Kakar
Kakar

Reputation: 5609

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

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.

Upvotes: 4

Views: 589

Answers (1)

while1
while1

Reputation: 3370

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

Upvotes: 3

Related Questions