Get any field of current logged in User in LWC

In my last post, you can see how to get current logged in user Id. sometimes we need some other fields too. here we can learn how to get any field of current logged in user without calling apex class. 

get-user-details-lwc

Get Current User Details in LWC

1. First we need to get the current logged in user id.

import Id from '@salesforce/user/Id';
2. Using this current logged in user Id we can call the getRecord method of uiRecordApi to get any field value of that user.
If you don't' know how to use getRecord check it out my previous post of Update any record without using apex class in LWC.
import { getRecord } from 'lightning/uiRecordApi';
Now let's check with an example component.

getCurrentUserDetails.html

<template>
    <lightning-card title="Get Current User Details" icon-name="standard:user">
        <div class="slds-m-around_medium">
            <p>User Id: {userId} </p>
            <p>User Name: {name} </p>
            <p>User Email: {email} </p>
        </div>
    </lightning-card>
</template>

getCurrentUserDetails.js

import { LightningElement , wire} from 'lwc';
import Id from '@salesforce/user/Id';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/User.Name';
import EMAIL_FIELD from '@salesforce/schema/User.Email';

export default class GetCurrentUserDetails extends LightningElement {
    userId = Id;
    name;
    email;
    error;

    @wire(getRecord, { recordId: Id, fields: [NAME_FIELD, EMAIL_FIELD]}) 
    userDetails({error, data}) {
        if (data) {
            this.name = data.fields.Name.value;
            this.email = data.fields.Email.value;
        } else if (error) {
            this.error = error ;
        }
    }
}

getCurrentUserDetails.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation