Get Current User Id in LWC
Sometimes we need current user or logged in user id in our lightning web component. So salesforce OOTB can provides without calling apex class. as of now it does only support Id field of user. On my next post check how we can get any field of current user.
Let's follow the below steps to get the current user id in lwc.
1. First we have to import Id from @salesforce/user/Id.
[import Id from '@salesforce/user/Id';]
2. Then assign that Id to any var to use in you html file.
[userId = Id;]
Let check with an example component.
getCurrentUserId.html
[<template><lightning-card title="Get Current User Id" icon-name="standard:user"><div class="slds-m-around_medium"><p>User Id: {userId} </p></div></lightning-card></template>]
getCurrentUserId.js
[import { LightningElement } from 'lwc';import Id from '@salesforce/user/Id';export default class GetCurrentUserId extends LightningElement {userId = Id;}]
getCurrentUserId.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>]
You can also find the above code in SWDC WORLD repo.
COMMENTS