Lightning Web Component - How to get User Information without using Apex


Lightning Web Component - How to get User Information without using Apex


 Hi Trailblazer

In this blog, I will talk that how you can retrieve Logged-In user information in the Lightning Web component without using Apex Controller.

Using a Lightning web component without calling an Apex class to get the value of user object fields.

When designing a user interface, you frequently need to display the logged-in user interface. All other fields are typically fetched by calling an apex class, although Salesforce provides a direct method for obtaining the user's ID.

In LWC, you can get useful information without having to use a server-side apex method. We'll see how this can be done in this blog. A code to get user information is below

HTML File


<template>
    <div class="slds-box slds-theme_default">
        Logged in User is {name} with Username- {userName}.
    </div>
</template>


JavaScript File


import { LightningElement, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import nameField from '@salesforce/schema/User.Name';
import userNameField from '@salesforce/schema/User.Username'
import userEmailField from '@salesforce/schema/User.Email';
import userId from '@salesforce/user/Id';
export default class GetLoggerInInfo extends LightningElement {
 
    @track name;
    @track userName;
    @track email;
    @track error;
 
    @wire(getRecord, {
        recordId: userId,
        fields: [nameField, userEmailField,userNameField]
    }) wireuser({
        error,
        data
    }) {
        if (error) {
           this.error = error ; 
        } else if (data) {
            this.name = data.fields.Name.value;
            this.userName = data.fields.Username.value;
            this.email = data.fields.Email.value;
        }
    }

}


Note: Every field needs to have ".value" mentioned. In contrast to what happens in the apex class, no direct value can be retrieved.

In the preceding example, in order to retrieve Name, we must specify it as data.fields.Name.value;

Output


Let me know if you have doubts about any method in the comment below.

Till then! Happy coding


Next Post Previous Post
No Comment
Add Comment
comment url