Salesforce Asked by SFDC LWC on October 4, 2021
I need help in understanding the below issue. Looks like a bit weird one or might be i am not aware of basics of LWC. 3 ways to test and understand this :-
JS controller :-
export default class ParentWebComp extends LightningElement {
strVar='';
get message(){
return this.strVar='LWC getter';
}
connectedCallback(){
this.strVar='LWC connectedCallback';
}
handleClick(event){
this.strVar='Due to button Click';
}
HTML template:-
{message}<br/>
{strVar}<br/>
<lightning-button onclick={handleClick}/>
What are you doing is you are returning a hard coded value in the getter. Even if the connectedCallback is setting the value, that is being overridden by getter as you have hard coded it there. Same is the case with button click. Check this playground:- Playground
So, Basically if any property value change took place in component that has been referenced in the getter, getter will reevaluate its value.
To validate this, i have added another property which is not being used in getter and changing its value with button click. This does not trigger the getter to fire.
Now, I am going to change the property value used in getter via button click, this time as soon as you click the button, button handler changes the property value referenced in getter and that triggers getter to reevaluate its value.
To understand the connectedCallback, it fires when component gets loaded. It will not refire again once loaded. You might have heard of init handler in aura which does something on load of the component, connectedCallback does the same in Lightning web Component.
The big difference between use of getter and connectedCallback is:-
To solve your problem, you can remove the value assignment in getter. It will update the value accordingly.
strVar='';
get message(){
return this.strVar;
}
connectedCallback(){
this.strVar='LWC connectedCallback';
}
handleClick(event){
this.strVar='Due to button Click';
}
Correct answer by sanket kumar on October 4, 2021
Your problem is that your getter
is also assigning a value:
return this.strVar='LWC getter';
The result of this.strVar = 'LWC getter'
is true
(a boolean success value)
You should instead return
return this.strVar;
In the getter.
If you do this, the order of operations will be:
Initial assignment.
connectedCallback()
Button press (which causes a change that will make the getter run again)
Answered by Caspar Harmer on October 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP