"this" on React

Hey, in my componentWillMount method, I had to use the trick of

let that = this; in order to be able to update my state, my question is: is there a better way to do it without having to explicitly create that? Similar to how I don’t have to bind(this) when using arrow functions.

Just in case, here is my code:

componentWillMount() {
    let that = this;
    navigator.geolocation.getCurrentPosition(function(location) {
      fetchWeather(location.coords.latitude, location.coords.longitude)
        .then(data => {
          that.setState({
            data
          })
          console.log(data);
        })
    });
  }

I have tried with

navigator.geolocation.getCurrentPosition = location => {
      fetchWeather(location.coords.latitude, location.coords.longitude)
        .then(data => {
          this.setState({
            data
          })
          console.log(data);
        })
    }

But, it doesn’t even make it to send the request, so my question pretty much is, how to rewrite:

navigator.geolocation.getCurrentPosition(function(location) {
})

As an arrow function.

Thanks!

navigator.geolocation.getCurrentPosition((location)  => {
    //function body
});

or since location is the only parameter, the parentheses around it are optional so you could do

navigator.geolocation.getCurrentPosition(location  => {
    //function body
});
1 Like

Awesome, thank you so much!

Just for reference if someone needs it in the future:

navigator.geolocation.getCurrentPosition(location  => {
  fetchWeather(location.coords.latitude, location.coords.longitude)
    .then(data => {
      this.setState({
        temp: data.main.temp,
        pressure: data.main.pressure,
        humidity: data.main.humidity,
        city: data.name,
        loading: false
      })
  })
});