Change handler equivalent in Lightning Web Components

I recently started looking into Lightning Web Components.
Initially, I assumed that track decorator also acts like a change handler, But looks like I was wrong about it.

Is there any functionality in Lightning web components which is equivalent to

<aura:handler name="change" value="{!v.attriute}" action="{!c.handleChange}"/>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

No, there is no such equivalent. The intent of LWC is to prevent the various bugs of two-way binding that occurs in Aura. Instead, specify an event handler and respond to those changes:

<c-my-component somedata={value} onchange={updateData}></c-my-component>

While there’s some missing bits still (which I am assured is coming in the upcoming releases), you’ll need to adjust your way of thinking to using events to notify the parent object of changes.

Data destined to be set by a parent component must use @api instead of @track. For your internal data, use @track to get updates to those values inside your class.

Method 2

Well, there exists an standard equivalent defined in the docs:

https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.migrate_events

The point is substitute the variable definition, for example:

@api myVar;

Into getter and setter methods:

@api
get myVar(){
    return this._myVar;
}
set myVar(value){
    this._myVar=value;
    //Whatever logic o method to execute
}

I discovered that way trying to track an @api decorated variable to execute a function when the value is changed, but it can be extrapolated to other scenarios.

Hope it helps!!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x