How to get Current User Id, Record Id and Object API Name in LWC?

In this section, we will see how we can get the Logged-In User Id, Current Record Id and Object API Name by Lightning Web Component.

Thanks to Salesforce again to provide such a beautiful mechanism to get the Logged-In User Id, Current Record Id and Object API Name in Lightning Web Component without using Apex Class. Let’s see.

We have created a Lightning Web Component named “getCurrentIds”.

Step 1: Definitely, we have to update the getCurrentIds.js-meta.xml file to set the visibility in Lightning App Builder.

getCurrentIds.js-meta.xml

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

Step 2: We have updated the html file.

getCurrentIds.html

<template>
    <lightning-card title="Get Current Ids" icon-name="utility:ribbon">
        <lightning-layout vertical-align="center" multiple-rows="true">
            <lightning-layout-item padding="around-small">
                Current User Id: {userId}              
            </lightning-layout-item>
            <lightning-layout-item padding="around-small">
                Current Record Id: {recordId}
            </lightning-layout-item>
            <lightning-layout-item padding="around-small">
                Current Object API Name: {objectApiName}
            </lightning-layout-item>
        </lightning-layout>        
    </lightning-card> 
</template>

In this html file, we are showing the Logged-In User Id, Current Record Id and Object API Name.

Step 3: We have updated the JS file.

getCurrentIds.js

import { LightningElement,api } from 'lwc';
import CURRENTUSERID from '@salesforce/user/Id';

export default class GetCurrentIds extends LightningElement {

    userId = CURRENTUSERID;

    @api recordId;
    @api objectApiName;

}

To get the current Record Id and Object API Name, we have to declare the respective properties with @api annotation just like @api recordId, @api objectApiName and we need to place the component into Lightning Record Page. These are the case sensitive. To get the current User Id, we have to import User Id from @salesforce/user/Id.

Step 4: Need to place the component into Lightning Record Page.

Result

45,570 total views, 9 views today

Rating: 4.0/5. From 6 votes.
Please wait...

You may also like...