Unhandled Rejection (TypeError): this is undefined when write this.setState(data); in componentDidMount function
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);
});
}
}
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment