Get Current User Details in Lightning Web Components
Let’s discuss here how to get the current user details in lightning web components. To access the current user Id, import @salesforce/user/Id in a component’s JavaScript class. Note that @salesforce/user/ cannot be imported by itself; you must indicate the property that you want to import. For the User standard object, only the Id field is available.
import Id from '@salesforce/user/Id';
Option 1: Using Wire Service
You can able to get the current user details using getRecord wire adapter and you can able to pass the user id from the imported modules. Create a new lightning web component using the below SFDX command
sfdx force:lightning:component:create --type lwc --componentname userinfoexample --outputdir force-app\main\default\lwc
Use the below userinfoexample.html code
<template> Name : {name} Email :{email} </template>
Use the below userinfoexample.js code
import { LightningElement, wire, track } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; import USER_ID from '@salesforce/user/Id'; import NAME_FIELD from '@salesforce/schema/User.Name'; import EMAIL_FIELD from '@salesforce/schema/User.Email'; export default class Userinfoexample extends LightningElement { @track error ; @track email ; @track name; @wire(getRecord, { recordId: USER_ID, fields: [NAME_FIELD, EMAIL_FIELD] }) wireuser({ error, data }) { if (error) { this.error = error ; } else if (data) { this.email = data.fields.Email.value; this.name = data.fields.Name.value; } } }
Use the below userinfoexample.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld"> <apiVersion>45.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> </targets> </LightningComponentBundle>
Push changes and you can able to see the user details
Option 2: – Using apex class
you can able to get the user detail even using the apex class .create an Apex class that returns the user details as shown below
public class UserInfoDetails { @AuraEnabled(cacheable=true) public static User getUserDetails(String recId) { return [Select Id , Name ,Email from User where Id =:recId]; } }
update the userinfoexample.html with below code
<template> <template if:true={user}> Name : {user.Name} EMail : {user.Email} Id : {user.Id} </template> </template>
update userinfoexample.js code as shown below
import { LightningElement, wire, track } from 'lwc'; import getUserDetails from '@salesforce/apex/UserInfoDetails.getUserDetails'; import Id from '@salesforce/user/Id'; export default class Userinfoexample extends LightningElement { userId = Id; @track user; @track error; @wire(getUserDetails, { recId: '$userId' }) wiredUser({ error, data }) { if (data) { this.user = data; } else if (error) { this.error = error; } } }
Push changes and you can able to see the current logged in user details