0

I use such a pattern to get user's current position:

componentDidMount() {
       let lat, lon;
     navigator.geolocation.getCurrentPosition(function(location) {
         lat = location.coords.latitude;
         lon = location.coords.longitude;
 });
   setTimeout(() => {
    this.setState({
      lat,
      lon
    })
    console.log(this.state.lon, this.state.lat);
 }, 1000);
     }

It actually works but looks "patchy" because of setTimeout. The core problem is in some delay of getting location and console throws undefined without setTimeout. I tried a few another ways to fix it but all failed:

navigator.geolocation.getCurrentPosition(function(location) {
    this.setState({
         lat: location.coords.latitude,
         lon: location.coords.longitude
     })
 }).bind(this);

and humble let _this = this for example. Please, is there more wise way to setState, based on geolocation?

Seemax
  • 121
  • 12
  • Possible Duplicate of https://stackoverflow.com/questions/41278385/updated-state-not-reflecting-after-setstate/41278440#41278440 – Shubham Khatri Nov 13 '17 at 18:24
  • 1
    Make a slight modification on location of `.bind(this)` in `navigator.geolocation.getCurrentPosition(function(location) { this.setState({ lat: location.coords.latitude, lon: location.coords.longitude }) }.bind(this));` as you need to bind the callback function to `getCurrentPosition` and it will work. Also since setState is asyc, console.log() after setState wont accurately give you the correct result. Check the duplicate question – Shubham Khatri Nov 13 '17 at 18:25
  • @Shubham Khatri is correct. You could also use an arrow function instead of bind. – Rick Jolly Nov 13 '17 at 18:32

1 Answers1

2

As mentioned in the comments, you can either move your bind slightly or use an arrow function:

componentDidMount() {
    navigator.geolocation.getCurrentPosition(function (location) {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude 
      })
    }.bind(this));

    // OR
    navigator.geolocation.getCurrentPosition(location => {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude
      })
    });
}
Rick Jolly
  • 2,949
  • 2
  • 23
  • 31