Integration @PnP/Graph and SPFx – 1

I am planning to write series of articles to cover the @PnP/Graph artifacts. I am starting with @PnP/Graph/Users object.
Article provides the steps how to integrate PnP Graph in SPFx and best practices to initialize the class and call methods.
The SharePoint Development community also known as PnP Community.
An open source initiative coordinated by SharePoint engineering.
Let’s Start:

Create a new web part project
Click here to Setup SPFx Environment

yo @microsoft/sharepoint

Follow below steps to set solution Information
-What is your solution Name? <Provide Solution Name>
-Which baseline packages do you want to target for your component(s)? (Use arrow keys): SharePoint Online Only (latest)
Where do you want to place the files? (Use arrow keys): Create a subfolder with solution name
-Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites? N
-Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? N
-Which type of client-side component to create? (Use arrow keys): WebPart
Follow below steps to set WebPart information
-What is your Web part name?<Provide WebPart Name>
-What is your Web part description? (Test description) <Provide description>
-Which framework would you like to use?React
Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
npm shrinkwrap
code .

Install the library and required dependencies

npm install @pnp/logging @pnp/common @pnp/odata @pnp/graph --save

Click here to check package.json file.

Create a new Folder “Services” under path “directory\SolutionName\src

Click Here to check code structure.
Create a file IPnPGraphService.ts and copy below code

export interface IPnPGraphService{
  getCurrentUser():Promise<any[]>;
  getMatchingUser(email:string):Promise<any[]>;
  getPeopleAroundMe():Promise<any[]>;
}

Create a file PnPGraphService.ts and copy below code

import { IPnPGraphService } from "./IPnPGraphService";
import { Log } from "@microsoft/sp-core-library";
import { graph } from "@pnp/graph";
import "@pnp/graph/users";
export class PnPGraphService implements IPnPGraphService{
  public async getCurrentUser():Promise<any[]>{
    let myInfo:any[] = [];
    try {
      const currentUser = await graph.me();
      if(currentUser){
       myInfo=currentUser
      }
    } catch (error) {
      Log.error("",error);
    }
    return myInfo;
  }
  public async getPeopleAroundMe():Promise<any[]>{
    let peopleinfo:any[] = [];
    try {
      await graph.me.people().then((info)=>{
        peopleinfo = info
      }).catch((error)=>{
        Log.error("",error);
      })
    } catch (error) {
      Log.error("",error);
    }
    return peopleinfo;
  }
  public async getMatchingUser(email:string):Promise<any[]>{
    let info:any[] = [];
    try {
      await graph.users.getById(email).get().then((info)=>{
        info = info;
      });
    } catch (error) {
      Log.error("",error);
    }
    return info;
  }
}

So, Service is ready . let’s create a code how can we access this service to get the content from directory to SPFx.
Open file I<WebPartName>Props.ts and copy below code

import { PnPGraphService } from "../../../Services/PnPGraphService";

export interface IPnPGraphUsersProps {
  description: string;
  PnPGraphServiceInstance:PnPGraphService;
}

Create new file I<WebpartName>State.ts and copy below code

export interface IPnPGraphUsersState{
  loading:boolean;
}

Open file <WebpartName>Webpart.ts file add below lines
Click here to check code

import { IPnPGraphUsersProps } from './components/IPnPGraphUsersProps';

private PnPGraphServiceInstance:PnPGraphService;
  public async onInit(){
    await super.onInit().then(()=>{
      graph.setup({
        spfxContext:this.context
      });
      this.PnPGraphServiceInstance = new PnPGraphService();
    });
  }

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

Open file WebpartName.tsx and add below lines of code
Click here to check code

import { IPnPGraphUsersState } from "./IPnPGraphUsersState";
constructor(props){
  super(props);

  this.state = {
    loading:true
  };
}

public componentDidMount(){
  this._getMe();
 }
 public _getMe(){
    this.setState({
      loading:true
    },async()=>{
      await this.props.PnPGraphServiceInstance.getCurrentUser()
      .then((myInfo)=>{
        console.log(myInfo);
      })
    })
 }
public getUserbyEmail(){
   this.setState({
     loading:true
   },async()=>{
     await this.props.PnPGraphServiceInstance.getMatchingUser("xyz@test.onmicrosoft.com")
     .then((userInfo)=>{
       console.log(userInfo);
     });
   });
 }

We need to set the scope of the API to get the information from graph API.
Open package-solution.json file in config directory.Add below lines in file.
Click here to understand the graph API scope and permission

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

Deploy the solution

gulp build
gulp bundle --ship
gulp package-solution --ship

Click here to get steps, how to deploy the solution

Once solution is deployed to SharePoint App Catalog.
Global Admin needs to approve the request to access the Graph API.
go to below URL
https://<TenantName>-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx?source=sitecollections#/webApiPermissionManagement
Approve the request and add your webpart on SharePoint Page.

Reference Links:
1. https://pnp.github.io/pnpjs/graph/
2. https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part
3. https://docs.microsoft.com/en-us/graph/permissions-reference
4. https://reactjs.org/docs/react-component.html
5.https://github.com/dips365/PnPGraphSamples/tree/master/PnPGraphUsersSample

Click here to provide your feedback.

Sharing Is Caring

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.