Get Loggedin User Details in LWC without Apex call

Getting user object fields value in Lightning web component without calling an Apex class.

While working on User Interface design, many times you need to display logged in user interface. Salesforce gives a way to get ID of logged in user directly, but all other fields are usually fetched by calling an apex class.

There is a way in LWC where you can fetch User details without calling a server-side apex method. In this blog we will see how we can achieve this. Below is a code to fetch user details.

HTML file.

    <div class="slds-box slds-theme_default">
        Logged in User is {a_User_Name} and working in {a_User_DEPT} department.

JavaScript File.

import { LightningElement, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import a_NAME_Ref from '@salesforce/schema/User.Name';
import a_DEPT_Ref from '@salesforce/schema/User.Department';

import a_User_Id from '@salesforce/user/Id';

export default class Sample_Test_Component extends LightningElement {
    @track a_User_Name;
    @track a_DEPT_Ref;
    @track a_Error;

    @wire(getRecord, {
        recordId: a_User_Id,
        fields: [a_NAME_Ref, a_DEPT_Ref]
    }) wireuser({
    }) {
        if (error) {
           this.error = error ; 
        } else if (data) {
            this.a_User_Name = data.fields.Name.value;
            this.a_User_DEPT = data.fields.Department.value;

Note: You need to mention .value for every field. No direct value can be fetched like how it is done in apex class.

In above example, to fetch Name we need to mention it as data.fields.Name.value;


Sample Output.


@Salesforce Modules

Get Information About the Current User

getRecord using lightning/uiRecordApi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s