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.
Code
Install "sp-pnp-js" from node package manager as shown below.
- PS C:\XXXX\SPFxSolutions\SpFxRichTextEditor>npm install --save sp-pnp-js
Import "sp-pnp-js" to your tsx file.
- import * as pnp from "sp-pnp-js";
- /*Get Current Logged In User*/
- public async spLoggedInUserDetails(ctx: any): Promise<any>{
- try {
- const web = new pnp.Web(ctx.pageContext.site.absoluteUrl);
- return await web.currentUser.get();
- } catch (error) {
- console.log("Error in spLoggedInUserDetails : " + error);
- }
- }
Parameter - context to be passed to spLoggedInUserDetails method.
In the below example, I am storing Title,Id,Email in state variables for later use.
- private async loadUserDetails():Promise<void>{
- try{
- let userDetails = await this.spLoggedInUserDetails(this.props.ctx);
- this.setState({
- Name: userDetails.Title,
- UserId: userDetails.Id,
- EmailId: userDetails.Email,
- });
- }catch(error){
- console.log("Error in loadUserDetails : ", error);
- }
- }
- public componentDidMount(): void {
- this.loadUserDetails();
- }
Please feel free to share your comments.
Hope this helps !!!!!

Jason Clark (Mbcs)Posted Dec 21, 2021, 2:35 PM
Too many assumptions with this code. what is ctx and where did you define it? Far too many errors when i copy and paste this code into a vanilla SPFX React skeleton project. Please explain every step from scaffolding out the app to EVERY change you make to any file within the project.
kanth ecPosted Oct 14, 2020, 5:42 AM
HI, Can you share the entire code, Is it in react SPFX, I am new to SPFX and react so if you could share complete webpart will be helpful, many thanks in advance