Gijo Varghese
Gijo Varghese

Reputation: 11780

Data variable not updating from method in VueJS

I'm using the following code to get visitors zip code(pin code) from HTML5 geolocation API. However, I want to get that zip code and update it to a data variable 'pincode'. Below is the code I used, the value prints in console correctly. But not updating in 'pincode' variable.

export default {
    data(){
        return {
      pincode: 0,
        }
    },
    methods: {
    findPincode(){
      navigator.geolocation.getCurrentPosition(function (position) {
                var geocoder = new google.maps.Geocoder();
                var latLng   = new google.maps.LatLng(
                    position.coords.latitude, position.coords.longitude);
                geocoder.geocode({
                    'latLng': latLng
                }, function (results, status) {
                    for (var i = 0; i < results[0].address_components.length; i++) {
                        var address = results[0].address_components[i];
                        if (address.types[0] == "postal_code") {
                            console.log(address.long_name) // prints 680001
                            this.pincode = Number(address.long_name) // not working
                        }
                    }
                });
            });
        }    
    }
}

Upvotes: 3

Views: 2451

Answers (2)

Saurabh
Saurabh

Reputation: 73609

Instead of using function() syntax, you can use arrow function, which does not bind it's own this, arguments, super, or new.target., like following:

geocoder.geocode({
   'latLng': latLng
}, (results, status) => {
    for (var i = 0; i < results[0].address_components.length; i++) {
       var address = results[0].address_components[i];
       if (address.types[0] == "postal_code") {
          console.log(address.long_name) // prints 680001
          this.pincode = Number(address.long_name) // not working
       }
   }
});

Upvotes: 5

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

This is because you lost the context to this inside your geocoder.geocode function

let self = this
geocoder.geocode({
   'latLng': latLng
}, function (results, status) {
    for (var i = 0; i < results[0].address_components.length; i++) {
       var address = results[0].address_components[i];
       if (address.types[0] == "postal_code") {
          console.log(address.long_name) // prints 680001
          self.pincode = Number(address.long_name) // not working
       }
   }
});

and that should work.

Upvotes: 9

Related Questions