2

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

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You've made my day. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.