Get Current User Profile Properties In SPFx Webpart Using MS Graph API

In this article, I have explained how to get the current user profile properties in your SPFx webpart using Microsoft Graph API

Create a SPFx project with “Webpart” template & choose the framework “React”

Install the necessary “NPM” packages and am going to use “MSGraphClient” to connect my webpart SPFx with Microsoft Graph API

npm install @microsoft/microsoft-graph-types --save-dev

Microsoft graph types help us to catch the error in your Typescript code faster.

Import the necessary packages in “MyUserInformation.tsx” file under “src\webparts\components

import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';

Open “IMyUserInformationProps” properties interface import the web part context from sp-webpart-base

import { WebPartContext } from "@microsoft/sp-webpart-base";

Add the “WebPartContext” properties inside the interface the final code look like below

import {WebPartContext } from "@microsoft/sp-webpart-base";
export interface IMyUserInformationProps {
  description: string;
  context: WebPartContext
}

Open “MyUserInformationWebPart.ts” include the context inside render()

public render(): void {
    const element: React.ReactElement<IMyUserInformationProps> = React.createElement(
      MyUserInformation,
      {
        context: this.context,
        description: this.properties.description,       
      }
    );
    ReactDom.render(element, this.domElement);
  }

Create a state interface to hold the data of user profile object

export interface IUserInformationState {
  data: {}
}

Initialize the constructor to declare the props and state

export default class MyEvents extends React.Component<IMyEventsProps, IUserInformationState> { 
  constructor(props: IMyEventsProps) {
    super(props);
      this.state = {
        data: {}
      }
  }

Create a function named “GetMyProfile()” to fetch the current user information

const GetMyProfile = () => {
    this.props.context.msGraphClientFactory.getClient('3').then((client): void => {
      client.api('me').get((error, user: MicrosoftGraph.User, rawResponse?: any) => {
        this.setState({
          data: user
        })
}

In “ComponetDidMount()” pass the created function it will retrieve the user information when page renders

componentDidMount(): void {
    this.GetMyProfile()
  }

Create a child component "UserDetail.tsx" to display user information details. Here I am using parent and child concept in components and send the retrieved data over props

Include the properties interface in your class component look like below

Import the UserDetail.tsx child component in to your parent component “MyUserInformation.tsx”

import UserDetail from './UserDetail';

Inside the render() method pass the component and data over props

public render(): React.ReactElement<IMyUserInformationProps> {        
return (
    <UserDetail data={this.state.data}></UserDetail>
    );  
}

Now open the child component “UserDetail.tsx” get the data from the props and render it into your HTML element based on your UI.

Full code

MyUserInformation.tsx

import * as React from 'react';
import styles from './MyUserInformation.module.scss';
import { IMyUserInformationProps } from './IMyUserInformationProps';
import { escape } from '@microsoft/sp-lodash-subset';
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
import UserDetail from './UserDetail';

export interface IUserInformationState {
  data: {}
}

export default class MyUserInformation extends React.Component<IMyUserInformationProps, IUserInformationState> {

  constructor(props: IMyUserInformationProps) {
    super(props)
    this.state = {
      data: {}
    }
  }

  //Connect to Graph API fetch the user information object
  GetMyProfile = () => {
    this.props.context.msGraphClientFactory.getClient('3').then((client): void => {
      client.api('me').get((error, user: MicrosoftGraph.User, rawResponse?: any) => {
        console.log(user)
        if (user) {
          //set the user information object in state property
          this.setState({
            data: user
          })
        }
      })
    })
  }

  componentDidMount(): void {
    this.GetMyProfile()
  }

  public render(): React.ReactElement<IMyUserInformationProps> {

    return (
      <UserDetail data={this.state.data}></UserDetail>
    );
  }
}

UserDetail.tsx

import * as React from 'react';
export interface IUserInformationProps {
    data: any
  }
class UserDetail extends React.Component <IUserInformationProps> {
    constructor(props: IUserInformationProps){
        super(props)
    }
    render() {
        return (
            <div>
              <p style={{fontWeight: "bold"}}>My User Information:</p>
              <li>
              <i>{this.props.data.mail} </i></li>
              <li><i>{this.props.data.displayName} </i></li>              
              <li><i>{this.props.data.businessPhones} </i></li>             
            </div>
        );
    }
}

export default UserDetail;

Before running the webpart include the below permission scopes inside your package-solution.json, You can include multiple permission scopes based on your application requirement

"webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "User.Read.All"
      }],

After a successful deployment of your webpart, Open SharePoint admin center choose “Advanced -> API Access” from left navigation window.

Approve your permission scope “User.Read.All” is displayed on “Pending requests”

Hit “Gulp Serve” and run the webpart