salesforcesalesforce-lightningsubscribemutationlwc

Run method when variable changes in lwc


I simply want to run a method when a variable changes. I think @track monitors the changes, but how do I run this method when it does? How do I write this?

 @track displayedData <---when this changes by any means, I want the below thing to run.

 handleDisplayedDataChanged() {
        console.log('run'); 
    }

Solution

  • You'll want to use a getter-setter: https://developer.salesforce.com/docs/platform/lwc/guide/js-props-getters-setters.html

    @track is only needed if the variable is an object or array: https://help.salesforce.com/s/articleView?id=release-notes.rn_lwc_track.htm&release=224&type=5

    Edit: so your code would be:

       displayedDataVar; //gave it a unique name
    
      @api
      get displayedData() {
        return this.displayedDataVar;
      }
      set displayedData(value) {
        this.displayedDataVar= value;
        console.log('run'); 
      }
    

    Edit2: apologies, I see that the example code was wrong, and have corrected it! See code below on how to use displayedData variable:

    connectedCallback(){
        displayedData = 'some string value'; //this will print 'run' in the console
    }