c-poulsen c-poulsen - 23 days ago 12
Javascript Question

Axios fetch in react

I need some assistent in using Axios in my react app. I use it in combination with geolocation to get the users location and use it in the api call with Axios.

My code is:

componentDidMount() {
if (navigator.geolocation){

function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var th = this;
this.serverRequest =
axios.get(`https://api.darksky.net/forecast/APIKEY/`+latitude+`,`+longitude+`?units=auto`)
.then(result => {
th.setState({
daily: result.data.daily.data,
loading: false,
error: null
});
})
.catch(err => {
// Something went wrong. Save the error in state and re-render.
this.setState({
loading: false,
error: err
});
});
};
function error() {
console.log( 'geolocation error' )
};
navigator.geolocation.getCurrentPosition(success, error);
}
}


but i end up with the error
Uncaught TypeError: Cannot set property 'serverRequest' of undefined

Answer

When success is called as a callback, its this value won't be right - in your case it's undefined. You can fix this by using bind on your callback function:

navigator.geolocation.getCurrentPosition(success.bind(this), error);