How to fetch current user data in LWC

Telegram logo Join our Telegram Channel

In this post let us see how we can fetch user information from fields like UserName, Email, FirstName, LastName in Lightning web components. We will use standard import to fetch the User Id and the wired method to fetch other user fields.


Code

userInfo.js

import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

import USER_NAME from '@salesforce/schema/User.Username';
import FIRST_NAME from '@salesforce/schema/User.FirstName';
import LAST_NAME from '@salesforce/schema/User.LastName';

import USER_ID from '@salesforce/user/Id';
export default class UserInfo extends LightningElement {
    userId = USER_ID;
    
    @wire(getRecord, { recordId : "$userId", fields: [USER_NAME, FIRST_NAME, LAST_NAME]})
    user;

    get userName(){
        return getFieldValue(this.user.data, USER_NAME);
    }

    get firstName(){
        return getFieldValue(this.user.data, FIRST_NAME);
    }

    get lastName(){
        return getFieldValue(this.user.data, LAST_NAME);
    }
}

userInfo.html

<template>
    <lightning-card variant="Narrow" title="User Info" icon-name="standard:user">
        <div class="slds-p-horizontal_small">User Id = {userId}</div>
        <div class="slds-p-horizontal_small">Username = {userName}</div>
        <div class="slds-p-horizontal_small">First Name = {firstName}</div>
        <div class="slds-p-horizontal_small">Last Name = {lastName}</div>
    </lightning-card>
</template>

userInfo.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>51.0</apiVersion>
	<isExposed>true</isExposed>
	<masterLabel>User Info</masterLabel>
	<description>User fetch info in LWC demo</description>
	<targets>
		<target>lightning__RecordPage</target>
		<target>lightning__AppPage</target>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com