0

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'); 
    }

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks! where are you using displayedDataVar?
You should think of that as a placeholder. You just use displayedData as if it is a normal variable.
I think connect callback only runs before rendering the component, where as I was hoping for any time the variable changes. But perhaps the element that uses it has events that do this? Idk
The connected callback was just an example of where you could use it. This will also work if any other function/logica changes the value. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.