3

I have a lwc that references {recordName} in the html. Going to the JavaScript I have a @wire getRecord call to retrieve a record and its name, the record being set to a variable.

I also have a get recordName() method that returns the name value from the record variable. It doesn’t set anything.

The record name in the html is populated fine and everything works with the above conditions. However, when I have a variable called recordName at the top in my JS, the recordName doesn’t get populated anymore.

Is this because properties/variables hold precedence over getters? And because the recordName variable isn’t set anywhere, it’s empty? Even if I have a getter that returns a value for recordName.

5

For a given name, you either have a property OR you have a get (and set) function, never both because as you see the LWC processing will be messed up. That's because of how JavaScript's property getters and setters work. You define a property using an appropriate name. But if you define a getter or setter you are re-defining that property to be handled by function(s) as covered in the Mozilla JavaScript reference documentation:

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value

There are conventions to deal with this using "_" as a prefix to indicate a "private" value, for example:

export default class MyLWC extends LightningElement {
   // The record
   record;
   
   // A "private" property on the LWC
   _recordName;

   get recordName() {
       return this._recordName;
   }

   @wire(getRecord, {...})
   receiveRecord({error, data}) {
       if (error) {
           ...
       } else if (data) {
           this.record = data;
           this._recordName = data.Name;
       }
    }
}

That said, I'd stick with a get-only recordName property (using the getter) and have this obtain the data direct from the record.

Take a look at the documentation for more details.

  • 1
    Thanks this cleared things up! Also, for the track tag in front of the getter, can you expand on your use of that? – Franz Nov 26 '20 at 9:10
  • 2
    @Franz @track is not necessary here. LWC uses this decorator to automatically update the UI when elements within the variable change, even if the variable itself does not change. Without @track, LWC will only update the UI if the actual value of the member changes. – sfdcfox Nov 26 '20 at 9:20
  • 1
    Most of my LWC development experience pre-dates when Salesforce removed the requirement for the @track. Since I wasn't sure if UI updates would work without this annotation on a getter I kept it there. But since @sfdcfox has said it isn't needed I'll assume that's correct and remove it from the answer. – Phil W Nov 26 '20 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.