I am creating a weather app using ReactJS. Following is my code:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
temp: ""
};
this.getLocation = this.getLocation.bind(this);
this.getWeather = this.getWeather.bind(this);
}
componentDidMount() {
this.getLocation();
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success,error);
}
else {
console.log("Not supported");
}
function success(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(lat,lon);
this.getWeather();
}
function error() {
console.log("Unable to retrieve your location");
}
}
getWeather() {
fetch(`http://api.weatherapi.com/v1/current.json?key=${api}&q=${lat},${lon}&aqi=no`)
.then((data) => data.json())
.then((item) => {
console.log(item);
});
}
api, lat and lon are constants I declared and initialized before this. This is giving the error:
Cannot read properties of undefined (reading 'getWeather')
at success
function success(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(lat,lon);
this.getWeather();
}
this
here refers to the success function
scope
use arrow function
success=(position)=>{
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(lat,lon);
this.getWeather();
}
or modify the whole code to
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success,error);
}
else {
console.log("Not supported");
}
const that = this; // now variable 'that' has the reference of 'this'
function success(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(lat,lon);
that.getWeather();
}
function error() {
console.log("Unable to retrieve your location");
}
}