[SalesForce] LWC Get record field values and render DOM elements conditionally

I want to create a custom component for a record page that gets a field value for the record, determines if the value is null or not. If it is null, some content will be shown and some will be hidden. If the value is not null, the opposite content will be shown/hidden.

Here's something I've tried:

HTML:

<template>
    <lightning-card
        title="Check Field Value"
        icon-name="standard:contact"
    >
        <template if:true={isNullTitleValue}>
            <div class="slds-var-m-around_medium">
                <p>I noticed this record does not have a value for the Title field.</p>
            </div>
        </template>
        <template if:false={isNullTitleValue}>
            <div class="slds-var-m-around_medium">
                <p>The value for the Title field is {title}.</p>
            </div>
        </template>
        <template if:true={contact.error}>
            <p>Error:{contact.error}</p>
        </template>
    </lightning-card>
</template>

JS:

import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

import TITLE_FIELD from '@salesforce/schema/Contact.Title';

const fields = [TITLE_FIELD];

export default class ConditionalRender extends LightningElement {
    @api recordId;
    @api objectApiName;

    @wire(getRecord, { recordId: '$recordId', fields })
    contact;

    get isNullTitleValue(){
        if(this.contact.data.fields.Title.value === null){
            return true;
        }
        return false;
    }

    get title() {
        return getFieldValue(this.contact.data, TITLE_FIELD);
    }
}   

When the component tries to load on the record page, this is the error message:

Error during LWC component connect phase: [Cannot read property 'fields' of undefined]

Please let me know where I took a wrong turn.

Best Answer

You already have a getter (title) that checks this properly (via getFieldValue), so you can just reuse it!

get isNullTitleValue(){
    return !this.title;
}
Related Topic