Sample Salesforce lightning/uiRecordApi to fetch data in Lightning Web Component without Apex

Sample Salesforce lightning/uiRecordApi to fetch data in Lightning Web Component without Apex

Sample Code:

HTML:

<template>
    <lightning-card>
        Account Name: {name}<br/>
        Website: {website}
    </lightning-card>
</template>

JavaScript:

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

const FIELDS = [ 'Account.Name', 'Account.Website' ];

export default class AccountQuickView extends LightningElement {

    @api recordId;
    accountRec;
    name;
    website;

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS } )
    wiredRecord( { error, data } ) {

        if (error) {

            let message = 'Unknown error';
            if ( Array.isArray( error.body ) ) {

                message = error.body.map(e => e.message).join( ', ' );

            } else if (typeof error.body.message === 'string' ) {

                message = error.body.message;

            }
            this.dispatchEvent(
                new ShowToastEvent( {
                    title: 'Error loading account',
                    message,
                    variant: 'error',
                } ),
            );
        } else if ( data ) {

            this.accountRec = data;
            this.name = this.accountRec.fields.Name.value;
            this.website = this.accountRec.fields.Website.value;

        }

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle> 

Output: 

Leave a Reply