Today we will see how to get Logged-in user info in LWC. For this, we will use lightning wire adapter.
Firstly, we will fetch the current user id by importing the “@salesforce/user/Id”, then pass the value to the lightning wire adapter for fetching the Name and other desired fields of the User. We use the UIRecordApi property to display the current User detail.
userInfo.html
<template> <lightning-card title="Logged in User Information" icon-name="standard:user"> <div class="slds-m-around_medium slds-list_horizontal slds-wrap"> <table class="slds-table slds-table_bordered slds-table_fixed-layout" border="1px solid" bordercolor="#dddbda" role="grid"> <tr> <th style="background:#FFC0CB;">Id</th> <td style="background:#00FFFF;">{userId}</td> </tr> <tr> <th style="background:#FFC0CB;">Name</th> <td style="background:#00FFFF;">{userName}</td> </tr> <tr> <th style="background:#FFC0CB;">Role</th> <td style="background:#00FFFF;">{userRoleName}</td> </tr> <tr> <th style="background:#FFC0CB;">Profile</th> <td style="background:#00FFFF;">{userProfileName}</td> </tr> </table> </div> </lightning-card> </template>
userInfo.js
/* * @description: get logged in user's detail * @author: sfdc4u.com */ import { LightningElement, wire, track } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; import Id from '@salesforce/user/Id'; import Name from '@salesforce/schema/User.Name'; import RoleName from '@salesforce/schema/User.UserRole.Name'; import ProfileName from '@salesforce/schema/User.Profile.Name'; export default class GetUserDetails extends LightningElement { userId = Id; userName; userRoleName; userProfileName; @wire(getRecord, { recordId: Id, fields: [Name, RoleName, ProfileName] }) userDetails({ error, data }) { if (error) { this.error = error; } else if (data) { if (data.fields.Name.value != null) { this.userName = data.fields.Name.value; } if (data.fields.UserRole.value != null) { this.userRoleName = data.fields.UserRole.value.fields.Name.value; } if (data.fields.Profile.value != null) { this.userProfileName = data.fields.Profile.value.fields.Name.value; } } } }
userInfo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>54.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> <target>lightning__AppPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
Output:
Also Read: Best Practices in Lightning Web Component
1 thought on “Get Logged-In User Info in LWC”