Reputation: 903
I have a problem related to how the react native decides to skip re-rendering altogether when I change a state in the component.
I have a drop-down menu which when one of its option is chosen, it will load the option of the next drop-down. In this case: country and city. All I currently want to do is to show 'Loading' text under the city drop-down when a country is chosen. Here is a snippet of my code:
onCountryChange(country) {
this.setState({loadingCity: true});
//looping country array here to get the list of city option
this.setState({loadingCity: false});
}
render () {
return (
<View>
<Text>Country</Text>
<View>
<Dropdown
style={{ height: 20, width: 300}} values={this.state.country_name}
selected={0} onChange={this.onCountryChange.bind(this)}/>
</View>
</View>
<View>
<Text>City</Text>
{ this.state.selectedCountry != '' ?
<View>
<Dropdown
style={{ height: 20, width: 300}} values={this.state.city_name}
selected={0} onChange={this.onCityChange.bind(this)}/>
</View>
:
<Text>Please pick a country first</Text>
}
{ this.state.loadingCity?
<View>
<View>
<Image
style={{height: 10, width: 10}}
source={require('./images/loading.gif')} />
</View>
<Text>Loading</Text>
</View>
:
null
}
</View>
)
}
I tried to remove the line of code this.setState({loadingCountry: false})
and it actually shows the loading text. But apparently, react native skips the render related to loadingCountry altogether when I add the line of code back. Is there any way to force the loading to appear? I already tried using this.forceUpdate()
, however it still does not work.
Update: this is what I've tried to do using Timer Mixin:
onCountryChange(country) {
this.setState({loadingCity: true});
//looping country array here to get the list of city option
this.setTimeout(this.setState({loadingCity: false}),100000);
}
But for some reasons, the setTimeout did not actually wait for 100s to fire the this.setState({loadingCity: false})
function.
Upvotes: 1
Views: 705
Reputation: 748
Calling setState({loadingCity: true})
then setState({loadingCity: false})
in the same synchronous code block won't render. Even if it did, it would probably be a flash quicker than you'd see.
If you want the loading indicator to stay, don't set it false.
If you only want it visible for a few seconds, wrap the setState({loadingCity: false})
in a setTimeout (though dont forget to use react-timer-mixin).
Upvotes: 0