[SalesForce] Accessing / Dealing with Undefined Variables returned from Apex Method in LWC

An issue with the Apex controller / LWC interaction is that when retrieving values from an Apex controller / method the returned object will not bring back object properties that do not have values.

for example if we are trying to retrieve an Account from the database, we use @wire, call the apex method and within the Apex method utilize a query to retrieve necessary values.

return SELECT Id, Name, Occupation__c from Account LIMIT 1

the issue is that if Occupation__c is null in the database, then the field name "Occupation__c" is not even returned in the object passed back to the LWC. Which brings me to my question, how best to handle this in LWC?

currently I am using this method to "validate" the values coming back from the Apex method

 this.account = {
                AccountId: data.Id,
                OwnerId: data.OwnerId ? data.OwnerId : "",
                Occupation: data.Occupation__c ? data.Occupation__c : "",
                }

My Question is, is this a more efficient way to do this, is this best practice? does Salesforce have any examples to reference?

Best Answer

Well,

// account.js
import { LightningElement, wire, track } from 'lwc';

// Wire adapter to load records.
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ID_FIELD from '@salesforce/schema/Accoun.Id';
import OCUPATION_FIELD from '@salesforce/schema/Account.Occupation__c';

export default class AccountDetail extends LightningElement {
   // Id of Account to display.
   recordId;

   // Wire to object //
   @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD, ID_FIELD, OCUPATION_FIELD] })
   account;

   get name() {
        return getFieldValue(this.account.data, NAME_FIELD);
   }

   get ocupation(){
        return getFieldValue(this.account.data, OCUPATION_FIELD);
   }

}

You can get more information here: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_wire_adapters_record

The best approach if you still want to use the apex controler is save the data in an object and then resolve those using getters:

@wire(getMyAccount) wiredAccount({ data }) {
    if (data) {
        this.account = data;
    } 
}

get name() {
    return this.account && getSObjectValue(this.account, NAME_FIELD); }

More info here: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/apex