SharePoint Framework - Retrieve User Profile Information

User Profile service in SharePoint is useful to store information related to users. SharePoint out of box provides various user profile properties to denote user attributes (e.g. Id, First Name, Last Name, Manager, etc.). We can also create our own custom user profile properties. In this article, we will explore how to retrieve the user profile information. We will use ReactJS in this example.

Overview

User Profile service in SharePoint is useful to store information related to users. SharePoint out-of-box provides various user profile properties to denote user attributes (e.g. Id, First Name, Last Name, Manager, etc.). We can also create our own custom user profile properties.
 
In this article, we will explore how to retrieve the user profile information. We will use ReactJS in this example.

User Profile in SharePoint Online

  1. Open https://[tenant]-admin.sharepoint.com.
  2. From left navigation, click "user profiles".

    SharePoint Framework - Retrieve User Profile Information
User profile properties and user profiles can be managed from here.

Create SPFx Solution

Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-react-userprofile  
Navigate to the above-created directory.
  1. cd spfx-react-userprofile  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman Generator will present you with the wizard by asking questions about the solution to be created.
 
SharePoint Framework - Retrieve User Profile Information 
  
Solution Name
Hit Enter to have the default name (spfx-react-userprofile in this case) or type in any other name for your solution.
 
Selected choice - Hit Enter 
 
Target for component 
Here, we can select the target environment where we are planning to deploy the client webpart, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
 
Selected choice - SharePoint Online only (latest) 
 
Place of files 
We may choose to use the same folder or create a subfolder for our solution.
 
Selected choice - Same folder 
 
Deployment option 
Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
 
Selected choice - N (install on each site explicitly) 
 
Type of client-side component to create
We can choose to create client side webpart or an extension. Choose the webpart option.
 
Selected choice - WebPart 
 
Web part name 
Hit Enter to select the default name or type in any other name.
 
Selected choice - UserProfileViewer 
 
Web part description 
Hit Enter to select the default description or type in any other value.
 
Selected choice - Fetch user profile values with SPFx 
 
Framework to use 
Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout).
 
Selected choice - React
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time. Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
  1. npm shrinkwrap  
In the command prompt, type the below command to open the solution in the code editor of your choice.
  1. code .  

Define Model for User Profile

Let us start by defining the model for user profile properties.
 
Add a file IUserProfile.ts under “src\webparts\userProfileViewer\components\” folder with the below content.
  1. export interface IUserProfile {  
  2.     FirstName: string;  
  3.     LastName: string;      
  4.     Email: string;  
  5.     Title: string;  
  6.     WorkPhone: string;  
  7.     DisplayName: string;  
  8.     Department: string;  
  9.     PictureURL: string;      
  10.     UserProfileProperties: Array<any>;  
Update IUserProfileViewerProps.ts under “src\webparts\userProfileViewer\components\” folder to include below properties.
  1. import { ServiceScope } from '@microsoft/sp-core-library';  
  2.   
  3. export interface IUserProfileViewerProps {  
  4.   description: string;  
  5.   userName: string;  
  6.   serviceScope: ServiceScope;  
  7. }  
Define State
 
Add the file IUserProfileViewerState.ts under folder “src\webparts\userProfileViewer\components\”.
  1. import { IUserProfile } from '../components/IUserProfile';  
  2.   
  3. export interface IUserProfileViewerState {  
  4.     userProfileItems: IUserProfile;  
  5. }  

Define Service

Now, we will define a service to fetch the user profile values.
  1. In the solution, create a new folder “services” at the same level of “components” folder.
  2. Create a new file “UserProfileService.ts” under it.
  1. import { ServiceScope, ServiceKey } from "@microsoft/sp-core-library";    
  2. import { IUserProfile } from '../components/IUserProfile';  
  3. import { IDataService } from './IDataService';   
  4. import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';    
  5. import { PageContext } from '@microsoft/sp-page-context';    
  6.    
  7. export class UserProfileService implements IDataService {  
  8.     public static readonly serviceKey: ServiceKey<IDataService> = ServiceKey.create<IDataService>('userProfle:data-service', UserProfileService);    
  9.     private _spHttpClient: SPHttpClient;  
  10.     private _pageContext: PageContext;    
  11.     private _currentWebUrl: string;    
  12.   
  13.     constructor(serviceScope: ServiceScope) {    
  14.         serviceScope.whenFinished(() => {    
  15.             // Configure the required dependencies    
  16.             this._spHttpClient = serviceScope.consume(SPHttpClient.serviceKey);  
  17.             this._pageContext = serviceScope.consume(PageContext.serviceKey);    
  18.             this._currentWebUrl = this._pageContext.web.absoluteUrl;    
  19.         });    
  20.     }  
  21.   
  22.     public getUserProfileProperties(): Promise<IUserProfile> {  
  23.         return new Promise<IUserProfile>((resolve: (itemId: IUserProfile) => void, reject: (error: any) => void): void => {    
  24.             this.readUserProfile()    
  25.               .then((orgChartItems: IUserProfile): void => {    
  26.                 resolve(this.processUserProfile(orgChartItems));    
  27.               });    
  28.           });  
  29.     }  
  30.   
  31.     private readUserProfile(): Promise<IUserProfile> {    
  32.         return new Promise<IUserProfile>((resolve: (itemId: IUserProfile) => void, reject: (error: any) => void): void => {    
  33.           this._spHttpClient.get(`${this._currentWebUrl}/_api/SP.UserProfiles.PeopleManager/getmyproperties`,    
  34.           SPHttpClient.configurations.v1,    
  35.           {    
  36.             headers: {    
  37.               'Accept''application/json;odata=nometadata',    
  38.               'odata-version'''    
  39.             }    
  40.           })    
  41.           .then((response: SPHttpClientResponse): Promise<{ value: IUserProfile }> => {    
  42.             return response.json();    
  43.           })    
  44.           .then((response: { value: IUserProfile }): void => {    
  45.             //resolve(response.value);    
  46.             var output: any = JSON.stringify(response);    
  47.             resolve(output);   
  48.           }, (error: any): void => {    
  49.             reject(error);    
  50.           });    
  51.         });        
  52.     }    
  53.   
  54.     private processUserProfile(orgChartItems: any): any {   
  55.         return JSON.parse(orgChartItems);    
  56.     }  
  57. }  

Code the WebPart

  1. Open UserProfileViewer.tsx under “src\webparts\userProfileViewer\components\” folder.
  2. Implement componentWillMount method.
  1. public componentWillMount(): void {  
  2.     let serviceScope: ServiceScope = this.props.serviceScope;    
  3.     this.dataCenterServiceInstance = serviceScope.consume(UserProfileService.serviceKey);  
  4.   
  5.     this.dataCenterServiceInstance.getUserProfileProperties().then((userProfileItems: IUserProfile) => {    
  6.       for (let i: number = 0; i < userProfileItems.UserProfileProperties.length; i++) {  
  7.         if (userProfileItems.UserProfileProperties[i].Key == "FirstName") {  
  8.           userProfileItems.FirstName = userProfileItems.UserProfileProperties[i].Value;  
  9.         }  
  10.   
  11.         if (userProfileItems.UserProfileProperties[i].Key == "LastName") {  
  12.           userProfileItems.LastName = userProfileItems.UserProfileProperties[i].Value;  
  13.         }  
  14.   
  15.         if (userProfileItems.UserProfileProperties[i].Key == "WorkPhone") {  
  16.           userProfileItems.WorkPhone = userProfileItems.UserProfileProperties[i].Value;  
  17.         }  
  18.   
  19.         if (userProfileItems.UserProfileProperties[i].Key == "Department") {  
  20.           userProfileItems.Department = userProfileItems.UserProfileProperties[i].Value;  
  21.         }  
  22.   
  23.         if (userProfileItems.UserProfileProperties[i].Key == "PictureURL") {  
  24.           userProfileItems.PictureURL = userProfileItems.UserProfileProperties[i].Value;  
  25.         }  
  26.       }  
  27.   
  28.       this.setState({ userProfileItems: userProfileItems });    
  29.     });   
  30.   }  
Implement render method to display user profile values.
  1. public render(): React.ReactElement<IUserProfileViewerProps> {  
  2.     return (  
  3.       <div className={ styles.userProfileViewer }>  
  4.         <div className={ styles.container }>  
  5.           <div className={ styles.row }>  
  6.             <div className={ styles.column }>  
  7.               <span className={ styles.title }>Welcome to SharePoint!</span>  
  8.               <p className={ styles.subTitle }>Fetch User Profile Properties</p>  
  9.                 
  10.               <img src={this.state.userProfileItems.PictureURL}></img>  
  11.                 
  12.               <p>   
  13.                 Name: {this.state.userProfileItems.LastName}, {this.state.userProfileItems.FirstName}  
  14.               </p>  
  15.   
  16.               <p>  
  17.                 WorkPhone: {this.state.userProfileItems.WorkPhone}  
  18.               </p>  
  19.                 
  20.               <p>  
  21.                 Department: {this.state.userProfileItems.Department}  
  22.               </p>                
  23.             </div>  
  24.           </div>  
  25.         </div>  
  26.       </div>  
  27.     );  
  28.   }  
Test the WebPart
  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx.
  4. Add the webpart to the page.
  5. The web part should display the information of the current logged-in user.

    SharePoint Framework - Retrieve User Profile Information

Troubleshooting

In some cases, SharePoint workbench (https://[tenant].sharepoint.com/_layouts/15/workbench.aspx) shows the below error although “gulp serve” is running.
 
SharePoint Framework - Retrieve User Profile Information 
 
Open the following URL in the next tab of the browser and accept the warning message.
 
https://localhost:4321/temp/manifests.js

Summary

User profile information can be displayed in SharePoint Framework webpart using the out of box available REST API.