Monday, October 21, 2019

How to get Current Logged in User information in Lightning Web Component(lwc)

This post explains how to get logged in user information in lightning web components(lwc)

check below post how to import current user id in lightning web components

To get the record details to use the getRecord wire adapter from 'lightning/uiRecordApi' scope module.
import { getRecord } from 'lightning/uiRecordApi';

HTML code
    <lightning-card title="Current Logged User Information">
        <template if:true={objUser}>
            <dl class="slds-list_horizontal slds-wrap" style="margin-left: 3%;">
                <dt class="slds-item_label slds-truncate" title="First Name">First Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.FirstName}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Last Name">Last Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.LastName}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Full Name">Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.Name}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Alias">Alias:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.Alias}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Active">Is Active:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.IsActive}</b></dd>

Javascript Controller 
import { LightningElement, track, wire} from 'lwc';

// importing to get the record details based on record id
import { getRecord } from 'lightning/uiRecordApi';

// impoting USER id
import USER_ID from '@salesforce/user/Id'; 

export default class CurrentUserDetailsInLWC extends LightningElement {

    @track objUser = {};
    // using wire service getting current user data
    @wire(getRecord, { recordId: USER_ID, fields: ['User.FirstName', 'User.LastName', 'User.Name', 'User.Alias', 'User.IsActive'] })
    userData({error, data}) {
        if(data) {
            window.console.log('data ====> '+JSON.stringify(data));

            let objCurrentData = data.fields;

            this.objUser = {
                FirstName : objCurrentData.FirstName.value,
                LastName : objCurrentData.LastName.value,
                Name : objCurrentData.Name.value,
                Alias : objCurrentData.Alias.value,
                IsActive : objCurrentData.IsActive.value,
        else if(error) {
            window.console.log('error ====> '+JSON.stringify(error))


Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="" fqn="CurrentUserDetailsInLWC">


No comments:

Post a Comment