TransWikia.com

vuejs not setting data property from arrow function

Stack Overflow Asked by Ahmed Nagi on February 5, 2021

I got this weird thing going on here:

I have this data property in vue

    data() {
        return {
            currentLat: 'intial Lat',
            currentLong: 'intial Long',
        };
    },
    mounted() {
        this.getCurrentLocation();
    },
    methods: {
        getCurrentLocation() {
            navigator.geolocation.getCurrentPosition((position) => {
                this.currentLat = position.coords.latitude;
                this.currentLong = position.coords.longitude;.

                console.log(this.currentLat); this prints 41.2111

            });
            console.log(this.currentLat); this prints 'intial Lat'
        },
    },

enter image description here

this.currentLat not set in the mount

I dont understand what’s happing here! it’s so weird!

3 Answers

Here is an example of converting to a promise and using async/await:

async getCurrentLocation() {
    const position = await new Promise(resolve => {
        navigator.geolocation.getCurrentPosition(position => resolve(position))
    });

    this.currentLat = position.coords.latitude;
    this.currentLong = position.coords.longitude;

    console.log(this.currentLat); // shouldn't print initial value
},

Answered by Washington Guedes on February 5, 2021

Your code is valid, the callback arrow function is asynchronous (it's not executed immediately) and the call of console.log(this.currentLat); is synchronous which makes it to be executed before the callback context, the property is properly if you use it inside the template it will work fine

Answered by Boussadjra Brahim on February 5, 2021

Set the values in a callback as follows:

<template>
  <div id="app">{{ currentLat }} - {{ currentLong }}</div>
</template>

<script>
export default {
  data() {
    return {
      currentLat: "intial Lat",
      currentLong: "intial Long",
    };
  },
  mounted() {
    this.getCurrentLocation();
  },
  methods: {
    getCurrentLocation() {
      navigator.geolocation.getCurrentPosition(this.setCoordinates);
    },
    setCoordinates(position) {
      this.currentLat = position.coords.latitude;
      this.currentLong = position.coords.longitude;
    },
  },
};
</script>

Answered by Majed Badawi on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP