LWC – How to Handle Null Value in Lightning Web Components

I am fetching contact address in js and setting the address in a variable which I am using in html to print the address.

Now suppose if contact mailing state is empty then in html its printing 'null'.
How can I handle this situation?

JS::

import STATE_FIELD from "@salesforce/schema/Contact.MailingState";
import COUNTRY_FIELD from "@salesforce/schema/Contact.MailingCountry";
export default class CustomerContact extends LightningElement {
    MailingAddress;
    @wire(getRecord, {
        recordId: "$recordId",
        fields: [COUNTRY_FIELD, STATE_FIELD],
    })
    wiredData({ error, data }) {
        if (data) {
            const street = getFieldValue(this.contactRecord, STREET_FIELD);
            const country = getFieldValue(this.contactRecord, COUNTRY_FIELD);
            this.MailingAddress = street + "," + country;
        }
    }
}

HTML::

<div>{MailingAddress}<div> 
//this is printing null Country Name if street is blank.

Best Answer

let street = '' // assign a default value is a good practice, we use an empty string here

if(getFieldValue(this.contactRecord, STREET_FIELD)) { street = getFieldValue(this.contactRecord, STREET_FIELD) //if it is not null reassign }

Or you can do it in one line

let street = getFieldValue(this.contactRecord, STREET_FIELD) ?getFieldValue(this.contactRecord, STREET_FIELD) : ''

Related Topic