Unhandled Rejection (TypeError): this is undefined when write this.setState(data); in componentDidMount function

Viewed 69

When I use this function without this.setState(data); everything is ok, and I see in the console the data from the API.

When I set this.setState(data); under console.log(data); I receive error like this:

Unhandled Rejection (TypeError): this is undefined
componentDidMount/<
src/App.js:42

  39 |       let data = await response.json();
  40 |       
  41 |       console.log(data);
> 42 |       this.setState(data);
     | ^  43 |     });
  44 |   }
  45 | }

The code:

     componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async function (position) {
        console.log("Latitude is :", position.coords.latitude);
        console.log("Longitude is :", position.coords.longitude);

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const response = await fetch(url);
        let data = await response.json();
        
        console.log(data);
        this.setState(data);
      });
    }
  }
1 Answers

The this scope has been changed. You need to use an arrow function or assign the this into another variable. You can change like -

navigator.geolocation.watchPosition(async (position) => {
    // Your code here...
});

Otherwise, you can preserve the this variable to another variable at the outer scope and use that inside.

componentDidMount() {
    if (navigator.geolocation) {
        // Keep the this to the self variable.
        const self = this;
        navigator.geolocation.watchPosition(async function (position) {
            // The other codes...
            self.setState(data);
        });
    }
}
Related