I recently tested my react native app on IOS and saw a strange bug : One of my setState call do not update my state, and i checked if everything else was correct.
I'm working on a real estate selling application. This setState was meant to, on a map, when the user click on a marker, shows a box of the estate clicked with detailled informations. So when a user click, it get the index of the estate clicked, and fill a state var currentEstate with it.
Furthemore it appears only on IOs, on Android everything is working fine, any ideas ?
Here's the code :
My toggle estate function, which contains the setState
_toggleEstate(index, coords) { // This is what i want to put in my currentEstate, and it's not empty console.log(this.state.estates[index]); this.setState( { currentEstate: this.state.estates[index] }, function() { // But this is empty, so the setState didn't work console.log(this.state.currentEstate); } ); var newRegion = { latitude: coords.latitude, longitude: coords.longitude, latitudeDelta: 0.00522, longitudeDelta: 0.0221 }; this.mapRef.animateToRegion(newRegion, 500); }
My renderEstate function which check if the currentEstate is empty and return a JSX component if not :
_renderEstateItem() { if (this._isEmpty(this.state.currentEstate)) { return null; } else { return (<View style={styles.estateContainer}><EstateItem estate={this.state.currentEstate} displayDetailForEstate={this._displayDetailForEstate} showImage={false} /></View> ); } }
And my JSX component :
render() { return (<View style={styles.mainContainer}><MapView initialRegion={{ latitude: 48.8691526048, longitude: 2.352065575453187, latitudeDelta: 0.1922, longitudeDelta: 0.0421 }} ref={ref => { this.mapRef = ref; }} onPress={() => this._clickOnMap()} style={{ flex: 1 }}> {this.state.markers.map((marker, index) => { const coords = { latitude: marker.lat, longitude: marker.lng }; return (<MapView.Marker key={index} coordinate={coords} title={this.state.estates[index].adress} description={ numeral(this.state.estates[index].price) .format("0,0") .replace(",", "") +"€" } pinColor={color.electricViolet} onPress={() => this._toggleEstate(index, coords)} /> ); })}</MapView><TouchableOpacity onPress={() => this._goToList()} style={ this._isEmpty(this.state.currentEstate) ? styles.listButton : styles.listButtonUp }><Image style={styles.listIcon} resizeMode="contain" source={require("../assets/images/purple_icons/List.png")} /></TouchableOpacity> // Here it is when it's suppose to render {this._renderEstateItem()} {this._displayLoading()}</View> ); }
And finally the constructor :
constructor(props) { super(props); this.mapRef = null; this.myResearch = this.props.navigation.state.params.myResearch; this.state = { isLoading: false, estates: [], markers: [], currentEstate: [] }; Geocoder.init(constants.GOOGLE_MAPS_API); this._displayDetailForEstate = this._displayDetailForEstate.bind(this); }
Thanks in advance !