c-poulsen c-poulsen - 1 year ago 223
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 =
.then(result => {
daily: result.data.daily.data,
loading: false,
error: null
.catch(err => {
// Something went wrong. Save the error in state and re-render.
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download