Tag Archives: Username

Get Current User Name In Lightning Component

Apex Controller:

public class SampleController {
    
    @AuraEnabled
    public static String getUserName() {
        return userinfo.getName();
    }
}

Lightning Component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" controller="SampleController" access="global" >
    <!--Declare Attributes-->
    <aura:attribute name="currentUserName" type="String"/>
    
    <!--Declare Handler-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
    
    <!--Component Start-->
    <div class="slds-m-around--xx-large">
        <div class="slds-text-heading_large">{!v.currentUserName}</div>
    </div>
    <!--Component End-->
</aura:component>

Lightning JS Controller:

({
    doInit : function(component, event, helper) {
        var action = component.get("c.getUserName");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                component.set("v.currentUserName", result);
            }
        });
        $A.enqueueAction(action);
    }
})