Know Current User Id, Record Id and Object API Name in LWC


Use Case:
You might be in need of building dynamic LWC component which will act based on your current Lightning record page. There are numbers of use cases like for this. Lets say, You need an lwc component which you need to place it on a Lightning record page to fetch a related record details for quick view based on  current record. In this blog we'll focus only to get important global Id.

A Quick View of our LtngFastIds LWC.











Jugar (Solution) :
This is not a Jugar 😉.  Salesforce provides a very simple way to fetch Current Record Id, Current User Id and Object API name as well in Lightning Web Component (LWC).

Here is a quick code snapshot:

1. LtngFastIds.html


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

2. LtngFastIds.js

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

export default class LtngFastIds extends LightningElement {
    @track userId = CURRENTUSERID;
    @api recordId;
    @api objectApiName;
}


A bit of explanation:

Here is what saleforce say about recordId:
When your component is invoked in a record context in Lightning Experience or in the mobile app, recordId is set to the 18-character ID of the record, for example: 001xx000003DGSWAA4. Learn more here.
About userId:Make sure you use export statement inorder to get Current Logged in UserId. Like below. More here.
import CURRENTUSERID from '@salesforce/user/Id';

And finally, Make sure you update you lwc LtngFastIds.js-meta.xml to make is availabale in app builder.

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

Tadaaa! Its done!
Cheers!


Comments