Toan Le
Toan Le

Reputation: 29

Set state on react native

I start learn react native and i see one error when i try set state and use after set but seem not working. Please help me or tell me why it is not working.

here is my code:

handlePressDetailsNews(navigator, dataRow){
    var ob = [{title: 'test'}]
    this.setState({ test: ob});
    Alert.alert(
        'Test Alert',
        'Title '+ this.state.test.title,
    )
}

And here is screen after i click to title for see alert: https://www.screencast.com/t/rBkiNbgaTpzQ

Thanks!

Upvotes: 1

Views: 515

Answers (1)

skwidbreth
skwidbreth

Reputation: 8454

Call your Alert function as a callback after setting the state, rather than just putting it after setting the state. Try this:

handlePressDetailsNews(navigator, dataRow){
    var ob = {title: 'test'}
    this.setState({ test: ob}, () => {
        Alert.alert(
            'Test Alert',
            'Title '+ this.state.test.title,
        )
    });
}

The main problem is that Alert.alert() is being triggered before the state has finished being updated, so by using a callback, you ensure that the state has been set before proceeding.

Also, notice that I changed ob from an array that contains one object to just a 'normal' object (removed the brackets). If you want to keep that as an array for some reason, then you wouldn't be able to access that value with this.state.test.title, it'd have to be this.state.test[0].title. Since the value of this.state.test would be the array [{title: 'test'}], you'd need to access the first item in the array (with [0]) and then get the value of title for that item in the array.

Upvotes: 2

Related Questions