React Native Change State With Unexpected Logging

1k Views Asked by At

For context, I am working on this React Native Tutorial

The way this logs confuses me. The following is the console output when I changed an empty input field by typing "a" then "b".

PropertyFinder

Console log

Here's my SearchPage class. Why does console.log('searchString = ' + this.state.searchString); show the previous value for this.state.searchString?

class SearchPage extends Component {

constructor(props) {
    super(props);
    this.state = { 
        searchString: 'london'
    };
}

onSearchTextChanged(event) {
    console.log('onSearchTextChanged');
    console.log('searchString = ' + this.state.searchString +
     '; input text = ' + event.nativeEvent.text );
    this.setState({ searchString: event.nativeEvent.text });
    console.log('Changed State');
    console.log('searchString = ' + this.state.searchString);
}

render () {
    console.log('SearchPage.render');
    return (
        <View style={styles.container}>
            <Text style = { styles.description }>
                Search for houses to Buy!
                </Text>
            <Text style = {styles.description}>
                Search by place name or search near your location.
            </Text>
            <View style={styles.flowRight}>
                <TextInput
                    style = {styles.searchInput}
                    value={this.state.searchString}
                    onChange={this.onSearchTextChanged.bind(this)}
                    placeholder='Search via name or postcode'/>
                <TouchableHighlight style ={styles.button}
                underlayColor = '#99d9f4'>
                    <Text style ={styles.buttonText}>Go</Text>
                </TouchableHighlight>
            </View>
        <TouchableHighlight style={styles.button}
            underlayColor= '#99d9f4'>
            <Text style={styles.buttonText}>Location</Text>
        </TouchableHighlight>
        <Image source={require('image!house')} style={styles.image}/>
        </View>
    );
}
}
1

There are 1 best solutions below

2
Colin Ramsay On BEST ANSWER

setState can be an asynchronous operation, not synchronous. This means that updates to state could be batched together and not done immediately in order to get a performance boost. If you really need to do something after state has been truly updated, there's a callback parameter:

this.setState({ searchString: event.nativeEvent.text }, function(newState) {
    console.log('Changed State');
    console.log('searchString = ' + this.state.searchString);
}.bind(this));

You can read more on setState in the documentation.

https://facebook.github.io/react/docs/component-api.html