@track not working in connectedCallbackLWC property is not reactive@track vs @api (Lightning Web Components)LWC: Attaching event Listener Programmatically not workingLightning web component slot is not working inside select?CSS animation in LWC not workingaura.redirect not working with LWCTrack Input value in LWCEmbedding LWC in Aura Component not working?LWC property is not reactiveLWC emp API track field is not rendering

Why do the US media keep claiming that Iran is violating their nuclear deal?

Short story trilogy about a human whose parents were missionaries to a planet of cat people

Novel where a serial killer lives (almost) forever by swapping bodies

What is the most efficient algorithm to compute polynomial coefficients from its roots?

MS in Mathematics, having trouble finding work outside teaching algebra

Could the Ancient Egyptian hieroglyphs have been deciphered without the Rosetta Stone with modern tech?

Multiple processes redirecting to the same file with >

Stream of Thought/Creeping Chill Interaction?

Hoping for a satisfying conclusion (a musical connect wall)

How do I test if regression slopes are statistically different?

Ask Google to remove thousands of pages from its index after cleaning up from hacked site

Is there a website about artificial intelligence that is constantly updated?

How can I negotiate remote work due to my phobia

"Cобака на сене" - is this expression still in use or is it dated?

Nested CiviEvents

What would make the internet go away?

Why do airports in the UK have so few runways?

Was the whistle-blower's (12 Aug 2019) complaint deemed credible?

How to get out of the Ice Palace in Zelda A link to the Past?

Everybody knows how to make magical items. What about magical "places"?

What deck size is ideal?

Possible executive assistant job scam

How do I protect myself from bad contracting jobs?

Why did dict.get(key) work but not dict[key]?



@track not working in connectedCallback


LWC property is not reactive@track vs @api (Lightning Web Components)LWC: Attaching event Listener Programmatically not workingLightning web component slot is not working inside select?CSS animation in LWC not workingaura.redirect not working with LWCTrack Input value in LWCEmbedding LWC in Aura Component not working?LWC property is not reactiveLWC emp API track field is not rendering






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









3

















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.










share|improve this question
































    3

















    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.










    share|improve this question




























      3












      3








      3








      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.










      share|improve this question















      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.







      lightning-web-components






      share|improve this question














      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 15 at 9:44









      Ravi Dutt SharmaRavi Dutt Sharma

      162 bronze badges




      162 bronze badges























          3 Answers
          3






          active

          oldest

          votes


















          4


















          this is quite funny in javascript, in connectedCallback this refers to component, but in showPosition as its async method, this is undefined, and thus you cannot set lat and long



          Usually, for this scenario, we pass the current component reference this to showPosition method like one here. But as per Mozilla document , you cant pass custom parameter to getCurrentPositionCallback



          You have to use fatArrow function for getCurrentPositionCallback.



          Thus your JS code will be:



          import LightningElement, track, api from 'lwc';

          export default class App extends LightningElement
          @track lat;
          @track lng;
          connectedCallback()
          console.log('Connected callback called'+ navigator.geolocation);
          console.log(JSON.stringify(navigator.geolocation));
          let myComponent = this;
          if (navigator.geolocation)
          navigator.geolocation.getCurrentPosition((position)=>
          console.log("position: ",position);
          console.log("position coords: ",position.coords);
          console.log("position coords lat: ",position.coords.latitude);
          myComponent.lat = position.coords.latitude;
          myComponent.lng = position.coords.longitude;
          console.log("lat: ",myComponent.lat);
          console.log("lng: ",myComponent.lng);
          );









          Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/htbBevIZr/2/edit






          share|improve this answer


























          • Thanks Pranay. Do you see any problem with below code:

            – Ravi Dutt Sharma
            Jul 15 at 10:44











          • connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

            – Ravi Dutt Sharma
            Jul 15 at 10:45






          • 1





            @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

            – Pranay Jaiswal
            Jul 15 at 11:27


















          4


















          The problem lies with how this behaves in JavaScript. I strongly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



          As to fixing your code, this one line change does the trick:



          navigator.geolocation.getCurrentPosition(showPosition.bind(this));


          You can read about bindat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind






          share|improve this answer























          • 1





            +1, There is always an elegant way in javascript.

            – Pranay Jaiswal
            Jul 15 at 13:57


















          0


















          this will be window object as functions in navigator returns promises - which makes it async methods/functions. I already answered this here:
          LWC property is not reactive



          However I am putting it here again:



          This pitfall is quite common for salesforce developers working on Javascript. Set-Interval actually changes the context of this to window as functions like setInterval, setTimeout etc are async functions and hence these functions run after the main thread has finished processing. This can be addressed by any of 2 options:



          1. Lexical Scoping - old fashioned (pls do a google search for understanding)

          2. Arrow functions - Modern javascript. (PFB)

          Just change the callback function from:



          setInterval(function(), 500);


          To



          setInterval(() => , 500);


          For simple understanding, Arrow functions don't have their own scope because of which it takes the scope of parent object.



          There are many other advantages of arrow functions.
          Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions






          share|improve this answer



























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "459"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );














            draft saved

            draft discarded
















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f269416%2ftrack-not-working-in-connectedcallback%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown


























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4


















            this is quite funny in javascript, in connectedCallback this refers to component, but in showPosition as its async method, this is undefined, and thus you cannot set lat and long



            Usually, for this scenario, we pass the current component reference this to showPosition method like one here. But as per Mozilla document , you cant pass custom parameter to getCurrentPositionCallback



            You have to use fatArrow function for getCurrentPositionCallback.



            Thus your JS code will be:



            import LightningElement, track, api from 'lwc';

            export default class App extends LightningElement
            @track lat;
            @track lng;
            connectedCallback()
            console.log('Connected callback called'+ navigator.geolocation);
            console.log(JSON.stringify(navigator.geolocation));
            let myComponent = this;
            if (navigator.geolocation)
            navigator.geolocation.getCurrentPosition((position)=>
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            myComponent.lat = position.coords.latitude;
            myComponent.lng = position.coords.longitude;
            console.log("lat: ",myComponent.lat);
            console.log("lng: ",myComponent.lng);
            );









            Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/htbBevIZr/2/edit






            share|improve this answer


























            • Thanks Pranay. Do you see any problem with below code:

              – Ravi Dutt Sharma
              Jul 15 at 10:44











            • connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

              – Ravi Dutt Sharma
              Jul 15 at 10:45






            • 1





              @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

              – Pranay Jaiswal
              Jul 15 at 11:27















            4


















            this is quite funny in javascript, in connectedCallback this refers to component, but in showPosition as its async method, this is undefined, and thus you cannot set lat and long



            Usually, for this scenario, we pass the current component reference this to showPosition method like one here. But as per Mozilla document , you cant pass custom parameter to getCurrentPositionCallback



            You have to use fatArrow function for getCurrentPositionCallback.



            Thus your JS code will be:



            import LightningElement, track, api from 'lwc';

            export default class App extends LightningElement
            @track lat;
            @track lng;
            connectedCallback()
            console.log('Connected callback called'+ navigator.geolocation);
            console.log(JSON.stringify(navigator.geolocation));
            let myComponent = this;
            if (navigator.geolocation)
            navigator.geolocation.getCurrentPosition((position)=>
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            myComponent.lat = position.coords.latitude;
            myComponent.lng = position.coords.longitude;
            console.log("lat: ",myComponent.lat);
            console.log("lng: ",myComponent.lng);
            );









            Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/htbBevIZr/2/edit






            share|improve this answer


























            • Thanks Pranay. Do you see any problem with below code:

              – Ravi Dutt Sharma
              Jul 15 at 10:44











            • connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

              – Ravi Dutt Sharma
              Jul 15 at 10:45






            • 1





              @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

              – Pranay Jaiswal
              Jul 15 at 11:27













            4














            4










            4









            this is quite funny in javascript, in connectedCallback this refers to component, but in showPosition as its async method, this is undefined, and thus you cannot set lat and long



            Usually, for this scenario, we pass the current component reference this to showPosition method like one here. But as per Mozilla document , you cant pass custom parameter to getCurrentPositionCallback



            You have to use fatArrow function for getCurrentPositionCallback.



            Thus your JS code will be:



            import LightningElement, track, api from 'lwc';

            export default class App extends LightningElement
            @track lat;
            @track lng;
            connectedCallback()
            console.log('Connected callback called'+ navigator.geolocation);
            console.log(JSON.stringify(navigator.geolocation));
            let myComponent = this;
            if (navigator.geolocation)
            navigator.geolocation.getCurrentPosition((position)=>
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            myComponent.lat = position.coords.latitude;
            myComponent.lng = position.coords.longitude;
            console.log("lat: ",myComponent.lat);
            console.log("lng: ",myComponent.lng);
            );









            Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/htbBevIZr/2/edit






            share|improve this answer














            this is quite funny in javascript, in connectedCallback this refers to component, but in showPosition as its async method, this is undefined, and thus you cannot set lat and long



            Usually, for this scenario, we pass the current component reference this to showPosition method like one here. But as per Mozilla document , you cant pass custom parameter to getCurrentPositionCallback



            You have to use fatArrow function for getCurrentPositionCallback.



            Thus your JS code will be:



            import LightningElement, track, api from 'lwc';

            export default class App extends LightningElement
            @track lat;
            @track lng;
            connectedCallback()
            console.log('Connected callback called'+ navigator.geolocation);
            console.log(JSON.stringify(navigator.geolocation));
            let myComponent = this;
            if (navigator.geolocation)
            navigator.geolocation.getCurrentPosition((position)=>
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            myComponent.lat = position.coords.latitude;
            myComponent.lng = position.coords.longitude;
            console.log("lat: ",myComponent.lat);
            console.log("lng: ",myComponent.lng);
            );









            Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/htbBevIZr/2/edit







            share|improve this answer













            share|improve this answer




            share|improve this answer










            answered Jul 15 at 10:30









            Pranay JaiswalPranay Jaiswal

            25.1k5 gold badges36 silver badges78 bronze badges




            25.1k5 gold badges36 silver badges78 bronze badges















            • Thanks Pranay. Do you see any problem with below code:

              – Ravi Dutt Sharma
              Jul 15 at 10:44











            • connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

              – Ravi Dutt Sharma
              Jul 15 at 10:45






            • 1





              @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

              – Pranay Jaiswal
              Jul 15 at 11:27

















            • Thanks Pranay. Do you see any problem with below code:

              – Ravi Dutt Sharma
              Jul 15 at 10:44











            • connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

              – Ravi Dutt Sharma
              Jul 15 at 10:45






            • 1





              @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

              – Pranay Jaiswal
              Jul 15 at 11:27
















            Thanks Pranay. Do you see any problem with below code:

            – Ravi Dutt Sharma
            Jul 15 at 10:44





            Thanks Pranay. Do you see any problem with below code:

            – Ravi Dutt Sharma
            Jul 15 at 10:44













            connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

            – Ravi Dutt Sharma
            Jul 15 at 10:45





            connectedCallback() let self = this; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); function showPosition(position) self.lat = position.coords.latitude; self.lng = position.coords.longitude;

            – Ravi Dutt Sharma
            Jul 15 at 10:45




            1




            1





            @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

            – Pranay Jaiswal
            Jul 15 at 11:27





            @RaviDuttSharma that will do. Fat Arrow functions are the elegant way to write inner function.

            – Pranay Jaiswal
            Jul 15 at 11:27













            4


















            The problem lies with how this behaves in JavaScript. I strongly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



            As to fixing your code, this one line change does the trick:



            navigator.geolocation.getCurrentPosition(showPosition.bind(this));


            You can read about bindat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind






            share|improve this answer























            • 1





              +1, There is always an elegant way in javascript.

              – Pranay Jaiswal
              Jul 15 at 13:57















            4


















            The problem lies with how this behaves in JavaScript. I strongly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



            As to fixing your code, this one line change does the trick:



            navigator.geolocation.getCurrentPosition(showPosition.bind(this));


            You can read about bindat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind






            share|improve this answer























            • 1





              +1, There is always an elegant way in javascript.

              – Pranay Jaiswal
              Jul 15 at 13:57













            4














            4










            4









            The problem lies with how this behaves in JavaScript. I strongly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



            As to fixing your code, this one line change does the trick:



            navigator.geolocation.getCurrentPosition(showPosition.bind(this));


            You can read about bindat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind






            share|improve this answer
















            The problem lies with how this behaves in JavaScript. I strongly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



            As to fixing your code, this one line change does the trick:



            navigator.geolocation.getCurrentPosition(showPosition.bind(this));


            You can read about bindat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind







            share|improve this answer















            share|improve this answer




            share|improve this answer








            edited Jul 15 at 13:56









            Pranay Jaiswal

            25.1k5 gold badges36 silver badges78 bronze badges




            25.1k5 gold badges36 silver badges78 bronze badges










            answered Jul 15 at 13:51









            Kevin VenkiteswaranKevin Venkiteswaran

            1,3605 silver badges13 bronze badges




            1,3605 silver badges13 bronze badges










            • 1





              +1, There is always an elegant way in javascript.

              – Pranay Jaiswal
              Jul 15 at 13:57












            • 1





              +1, There is always an elegant way in javascript.

              – Pranay Jaiswal
              Jul 15 at 13:57







            1




            1





            +1, There is always an elegant way in javascript.

            – Pranay Jaiswal
            Jul 15 at 13:57





            +1, There is always an elegant way in javascript.

            – Pranay Jaiswal
            Jul 15 at 13:57











            0


















            this will be window object as functions in navigator returns promises - which makes it async methods/functions. I already answered this here:
            LWC property is not reactive



            However I am putting it here again:



            This pitfall is quite common for salesforce developers working on Javascript. Set-Interval actually changes the context of this to window as functions like setInterval, setTimeout etc are async functions and hence these functions run after the main thread has finished processing. This can be addressed by any of 2 options:



            1. Lexical Scoping - old fashioned (pls do a google search for understanding)

            2. Arrow functions - Modern javascript. (PFB)

            Just change the callback function from:



            setInterval(function(), 500);


            To



            setInterval(() => , 500);


            For simple understanding, Arrow functions don't have their own scope because of which it takes the scope of parent object.



            There are many other advantages of arrow functions.
            Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions






            share|improve this answer






























              0


















              this will be window object as functions in navigator returns promises - which makes it async methods/functions. I already answered this here:
              LWC property is not reactive



              However I am putting it here again:



              This pitfall is quite common for salesforce developers working on Javascript. Set-Interval actually changes the context of this to window as functions like setInterval, setTimeout etc are async functions and hence these functions run after the main thread has finished processing. This can be addressed by any of 2 options:



              1. Lexical Scoping - old fashioned (pls do a google search for understanding)

              2. Arrow functions - Modern javascript. (PFB)

              Just change the callback function from:



              setInterval(function(), 500);


              To



              setInterval(() => , 500);


              For simple understanding, Arrow functions don't have their own scope because of which it takes the scope of parent object.



              There are many other advantages of arrow functions.
              Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions






              share|improve this answer




























                0














                0










                0









                this will be window object as functions in navigator returns promises - which makes it async methods/functions. I already answered this here:
                LWC property is not reactive



                However I am putting it here again:



                This pitfall is quite common for salesforce developers working on Javascript. Set-Interval actually changes the context of this to window as functions like setInterval, setTimeout etc are async functions and hence these functions run after the main thread has finished processing. This can be addressed by any of 2 options:



                1. Lexical Scoping - old fashioned (pls do a google search for understanding)

                2. Arrow functions - Modern javascript. (PFB)

                Just change the callback function from:



                setInterval(function(), 500);


                To



                setInterval(() => , 500);


                For simple understanding, Arrow functions don't have their own scope because of which it takes the scope of parent object.



                There are many other advantages of arrow functions.
                Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions






                share|improve this answer














                this will be window object as functions in navigator returns promises - which makes it async methods/functions. I already answered this here:
                LWC property is not reactive



                However I am putting it here again:



                This pitfall is quite common for salesforce developers working on Javascript. Set-Interval actually changes the context of this to window as functions like setInterval, setTimeout etc are async functions and hence these functions run after the main thread has finished processing. This can be addressed by any of 2 options:



                1. Lexical Scoping - old fashioned (pls do a google search for understanding)

                2. Arrow functions - Modern javascript. (PFB)

                Just change the callback function from:



                setInterval(function(), 500);


                To



                setInterval(() => , 500);


                For simple understanding, Arrow functions don't have their own scope because of which it takes the scope of parent object.



                There are many other advantages of arrow functions.
                Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions







                share|improve this answer













                share|improve this answer




                share|improve this answer










                answered Jul 17 at 19:08









                salesforce-sassalesforce-sas

                13.5k2 gold badges4 silver badges29 bronze badges




                13.5k2 gold badges4 silver badges29 bronze badges































                    draft saved

                    draft discarded















































                    Thanks for contributing an answer to Salesforce Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f269416%2ftrack-not-working-in-connectedcallback%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown









                    Popular posts from this blog

                    Tamil (spriik) Luke uk diar | Nawigatjuun

                    Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

                    Training a classifier when some of the features are unknownWhy does Gradient Boosting regression predict negative values when there are no negative y-values in my training set?How to improve an existing (trained) classifier?What is effect when I set up some self defined predisctor variables?Why Matlab neural network classification returns decimal values on prediction dataset?Fitting and transforming text data in training, testing, and validation setsHow to quantify the performance of the classifier (multi-class SVM) using the test data?How do I control for some patients providing multiple samples in my training data?Training and Test setTraining a convolutional neural network for image denoising in MatlabShouldn't an autoencoder with #(neurons in hidden layer) = #(neurons in input layer) be “perfect”?