Get Logged In User Email, Name And ID In SharePoint Framework (SPFx) Using PnP

In this blog, we will learn to retrieve SharePoint online logged in user details such as user email, user name and id properties from user context using Pnp in SharePoint framework.
In some scenarios, we might need to store user email, ID and user name in state variables for later use and the below example explains the steps to retrieve user details and store in an array for later usage. In this, I have used async/await function to handle the calls.
Install "sp-pnp-js"  from node package manager as shown below. 
  1. PS C:\XXXX\SPFxSolutions\SpFxRichTextEditor>npm install --save sp-pnp-js  

Import "sp-pnp-js" to your tsx file.

  1. import * as pnp from "sp-pnp-js";  
Below function retreives the logged in user details. 
  1. /*Get Current Logged In User*/  
  2. public async spLoggedInUserDetails(ctx: any): Promise<any>{  
  3.     try {  
  4.       const web = new pnp.Web(;  
  5.       return await web.currentUser.get();          
  6.     } catch (error) {  
  7.       console.log("Error in spLoggedInUserDetails : " + error);  
  8.     }      
  9. }  
Code Usage
Parameter - context to be passed to spLoggedInUserDetails method. 
In the below example, I am storing Title,Id,Email in state variables for later use. 
  1. private async loadUserDetails():Promise<void>{  
  2.     try{  
  3.       let userDetails = await this.spLoggedInUserDetails(this.props.ctx);  
  4.       this.setState({    
  5.         Name: userDetails.Title,    
  6.         UserId: userDetails.Id,    
  7.         EmailId: userDetails.Email,            
  8.       });  
  9.     }catch(error){  
  10.       console.log("Error in loadUserDetails : ", error);  
  11.     }  
  12. }  
Call this function in componentDidMount as shown below. 
  1. public componentDidMount(): void {  
  2.     this.loadUserDetails();  
  3. }  
Please feel free to share your comments.
Hope this helps !!!!!