Get Current Logged in User Details in LWC

Get Current User Details in Lightning Web Components or LWC Salesforce
Get Current User Details in Lightning Web Components Salesforce

Previously, I have told you how to use Lightning Navigation Service in Lightning Web Component. So Today, I am going to show you how you can get details of the Logged in user in LWC. For this, we will use lightning wire adapte.

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 of the User.

userDetails.html

<template>
   Hello {name}
</template>

So, by using the USER_ID property we will get the Current Logged in user, and we will be using this property further to fetch the details, you can obviously fetch any information about the current user and display them in LWC

userDetails.js

import { LightningElement, wire, track } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import USER_ID from '@salesforce/user/Id'; //this is how you will retreive the USER ID of current in user.
import NAME_FIELD from '@salesforce/schema/User.Name';
export default class userDetails extends LightningElement {
     @track error ;
     @track name;
     @wire(getRecord, {
         recordId: USER_ID,
         fields: [NAME_FIELD]
     }) wireuser({
         error,
         data
     }) {
         if (error) {
            this.error = error ; 
         } else if (data) {
             this.name = data.fields.Name.value;
         }
     }
 }

userDetails.js-meta.xml

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

Read my other intresting post, Toasts Notification in Lightning Web Component (LWC)

Get Information About the Current User

MoreoverIf you have any suggestions or issue with the post, you can reply in the comment box.

Support: For any further Salesforce support/ assistance or customisations, Chat with us

Parul Singh

I’m a Salesforce Certified Service Cloud Consultant, Certified Administrator & Certified Platform Developer. I have 2 years of experience, currently working on Field Service Lightning, Lightning Flows and Learning Lightning Web Component. I was featured in the top Salesforce Bloggers of 2018 by www.forcetalks.com

You may also like...