user10398929
user10398929

Reputation:

how to make componentDidMount() to finish before rendering

How do I make the page to render after componentDidMount finish.

All similar questions asked on here are given a solution that is specifically related to their problem

constructor(props){
  super(props);

  this.state = {

  region: {
  latitude: 0,
  longitude: 0,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}
  }
}

componentDidMount = () => {
   this.getMyLocation();
 };

getMyLocation = () => {

 navigator.geolocation.watchPosition(
   (position) => {

    const region = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      };
    this.setState({
      region: region
    })

   }
 );
}

render(){

<MapView
  provider={PROVIDER_GOOGLE}
  initialRegion={this.state.region}
  style = {styles.container}
  followUserLocation = {true}
  showsUserLocation = {true}

  ref="map"
  >

  </MapView>

 }

I was expecting the initialregion to be centered at the current user location but it instead is centered at latitude:0, longtuide:0 which is originally set under constructor

Upvotes: 0

Views: 82

Answers (2)

Ragu
Ragu

Reputation: 1728

You can move getMyLocation() to constructor

Try this way

constructor(props){
super(props);
this.getMyLocation();  
}

The Rule of function calling flow is:

1. Reducer functions called
2. Constructor called 
3. Render () called
4. ComponentDidMount() called

Upvotes: 0

t-benze
t-benze

Reputation: 486

I'm assuming that the initialRegion prop of your MapView can only be set once when the MapView component is constructed, in that case you should only render it when your location data is available. so you may change your render function to be something like.

render() {
  return this.state.region ? <MapView ... /> : <LoadingIndicator />;
}

And initialize your state.region to be null in constructor.

Upvotes: 2

Related Questions