+ Start a Discussion
Ravi Dutt SharmaRavi Dutt Sharma 

@track not working in connectedCallback

Hi,

In LWC, on the component load, I am fetching the latitude and longitude of the logged in user and trying to display it on the component. I have created two attributes named lat and lng and marked it with @track decorator so that whenever the value of these attributes is changed, the component will rerender automatically. I am setting the value of these attributes in connectedCallback, but the updated value is not getting reflected on the component. Below is the html and js files.
 
<template>
    <div class="slds-box">
        <div class="slds-text-heading--large">Weather Report - {lat} {lng}</div>
    </div>
</template>
 
import { LightningElement, track } from 'lwc';

export default class WeatherAppContainer extends LightningElement {
    @track lat;
    @track lng;
    connectedCallback() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
        
        function showPosition(position) {
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            this.lat = position.coords.latitude; 
            this.lng = position.coords.longitude; 
            console.log("lat: ",this.lat);
            console.log("lng: ",this.lng);
        }
    }

}

The console "position coords lat" prints the value correctly, but the next console statment does not get printed. I am guessing that we cannot use this keyword in the connectedCallback. Any pointers how to solve this? Thanks.
Meghna Vijay 7Meghna Vijay 7
Hi Ravi,

Can you post screenshot of your class method which you are using in this javascript controller?

Thanks
Ravi Dutt SharmaRavi Dutt Sharma
Hi Meghna,

Which class method you are referring to?
Ramakrishna Reddy GouniRamakrishna Reddy Gouni
Your tracking elements are not input elements. 
Ravi Dutt SharmaRavi Dutt Sharma
@Ramakrishna, I think it is not necesaary for tracking elements to be always input elements. Check this link for reference: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.js_props_private_reactive