Get Current User Details in Lightning Web Components

If you are a Salesforce developer or Admin the word hearing you most is Lightning Web components (LWC). If you still don’t have idea what they are then you should check my post in which I have explained Lightning Web Component and also created few sample Lightning Web Component.

Today we will check how we can get current user Id in Lightning web components. Using that Id we will fetch the user details and show them on UI. We will also do the same thing in Lightning so you can get the idea of both and can compare them side by side.

First we need to import user/Id and then we can use it in our code.

import { LightningElement, wire } from 'lwc';
import getUserInfo from '@salesforce/apex/UserDetails.getUserInfo';
import Id from '@salesforce/user/Id';

export default class LwcUserDetail extends LightningElement {

    @wire(getUserInfo, { userId: Id }) 

Using the wire we call the apex method and then bind the result with userData parameter. So as you can see we have achieved this using single line of code. Now if we need to achieve this in lightning

    init : function(component, event, helper) {
        var cuUserId = $A.get("$SObjectType.CurrentUser.Id");
        var action = component.get("c.getUserInfo");
            userId : cuUserId,

        action.setCallback( this, function(response){
            if(response.getState() === 'SUCCESS') {
               component.set("v.currentUser", response.getReturnValue());

So using $A.get("$SObjectType.CurrentUser.Id"); we can get the current user Id in Lightning.

Now in the UI both have different format.

In lightning we use {!} expressions

<aura:application controller="UserDetails" extends="force:slds">
    <aura:attribute name="currentUser" type="User" default="{'sObjecttype': 'User'}" />
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <lightning:card title="User Details in Lightning" iconName="action:user">
            {!v.currentUser.Name} <br/>

   <c:lwcUserDetail />

While in Lightning Web Component

    <lightning-card title="User Details in LWC" icon-name="action:user">
            <template if:true={}>
            <template if:true={userData.error}>
Lightning Web Components User Detail, Current User Id in Lightning Web Components

So we can see that syntax is different and LWS follow -in naming. Although both have similar attributes. So if you are planning to move your existing code into LWS then you can start by one component at a time.

You can also find complete code on my github-repo.

Do you want to add anything, let me know in comments. Happy programming 🙂


3 thoughts on “Get Current User Details in Lightning Web Components

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.