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";
Below function retreives the logged in user details.
-
- 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);
- }
- }
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.
- 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);
- }
- }
Call this function in componentDidMount as shown below.
- public componentDidMount(): void {
- this.loadUserDetails();
- }
Please feel free to share your comments.
Hope this helps !!!!!