How to Get Current logged in user id in SPFx using React Typescript


Manimekalai
Technology Specialist
Published On :   21 Mar 2018
Visit Count
Today :  4    Total :   3081



We can't use _spPageContextInfo inside a SPFx webpart, hence to get the current logged-in user name, email etc except user id please make use of below syntax.

this.context.pageContext.user doesn't include id or userId

When I don't want to make a rest call or other methods to get the current user Id!!!

Here is the solution

Add import pnp from 'sp-pnp-js'; in the top of webpart.ts file

clip_image002

Use the node.js command prompt to install below command to avoid the missing module error

npm install sp-pnp-js –save

Add the below code to your webpart.ts file

var email=this.context.pageContext.user.email;

this. getUserId (email);

public getUserId(email: string): Promise<number> {

return pnp.sp.site.rootWeb.ensureUser(email).then(result => {

return result.data.Id;

});

}

clip_image004

Thank you!

Categories