0

I am getting the user's location in componentDidMount, and it works well. However, after that, I am trying to change the state, and it does not register the change. Here is my constructor:

constructor(props){
 super(props);
 this.locationRetrieved = this.locationRetrieved.bind(this);
 this.state = {
 latitude: 30,
 longitude: 30
 }
}

and my locationRetreived function (hardcoding these for now):

locationRetrieved() {
this.setState({
  latitude: 78,
  longitude: 89
 });
}

and my componentDidMount:

   componentDidMount() {
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(success) { 
  this.locationRetrieved();
 },
  function(failure) {
    alert(failure);
    if(failure.message.indexOf("Only secure origins are allowed") == 0)   {
      // Secure Origin issue.
    }
  }); 
}
 else{
   alert("gelocation is not supported here");
  }
}

I have also tried directly setting state and not calling a function, like:

 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(success) { 
  this.setState({
    latitude: 45,
    longitude: 45
 })

},

but that does not work either. I know a location is retrieved, because when I do alert(success.coords.latitude) then the alert with my current latitude shows up.

The error console says:

 Uncaught TypeError: Cannot read property 'locationRetrieved' of undefined
at eval (eval at ./app/containers/CheckIn/index.js 

How can I set the state here once latitude/longitude are retrieved?

Thanks

jjjjjjjj
  • 4,203
  • 11
  • 53
  • 72
  • 2
    Even though you've bound your instance to the *function* that `this.locationRetrieved` refers to, that doesn't make `this` in your `geolocation` callback refer to your instance. From the error message, `this` is `undefined` within that callback (good! you're using strict mode). – T.J. Crowder Apr 28 '17 at 12:21
  • 1
    ok cool, the other guy here who answered it (but then deleted it) got the correct answer, i need to use: navigator.geolocation.getCurrentPosition((success) => { this.setState({ latitude: 1, longitude: 2 }); }); – jjjjjjjj Apr 28 '17 at 12:28
  • Yup -- which is covered in the linked question's answers. – T.J. Crowder Apr 28 '17 at 12:28

0 Answers0