1

How do I get the current user's groups which he is a part of without @pnp/sp js framework in SPFx ?

2

You can use spHttpClient built-in with SPFx.

The endpoint you need to consume is /_api/web/currentuser/groups.

Add the below import statement:

import { SPHttpClient } from '@microsoft/sp-http';

After that you can add the below code:

var siteGroupsData = await this.context.spHttpClient.get(this.context.pageContext.site.absoluteUrl 
+ "/_api/web/currentuser/groups",SPHttpClient.configurations.v1);
siteGroupsData.json().then(d => {

  var siteGroups = d.value;
  siteGroups.forEach(siteGroup => {
    console.log(siteGroup);
  });

});
  • getting error in "context" – user10000 Apr 18 at 14:52
  • Cannot read property 'get' of undefined – user10000 Apr 18 at 14:52
  • i wrote this method inside the render method of <webpartname>.ts file – Gautam Sheth Apr 18 at 14:54
  • I wrote it there only. – user10000 Apr 18 at 15:00
  • public render(): React.ReactElement<IReactGetItemsProps> { – user10000 Apr 18 at 15:00
1

First you need to import the library

import { CurrentUser } from '@pnp/sp/src/siteusers';

Then call the function to get the data

private getSPUserData(): void {      
  sp.web.currentUser.get().then((r: CurrentUser) => {  
    this.renderData(r['Title']);  
  });  
}

Where "r" is the SPUser Object, from this you can get

  • Email
  • LoginName
  • Title (Name)

Then you can user this query to ask fro the user groups

private getSPUserGroup(): void {      
  sp.web.currentUser.groups.get().then((r: any) => {  
    let grpNames: string ="";  
    r.forEach((grp: SiteGroup) =>{  
      grpNames += "<li>"+grp["Title"]+"</li>"  
    });      
    grpNames = "<ul>"+grpNames+"</ul>";  
    this.renderData(grpNames);  
  });  
}

Hope it can help you. Sya

  • This does not answer the question. OP specifically asks how to get a user's Group and to do so without the use of pnp. – FourthGenZ28 Apr 18 at 16:56
  • you're right i didn't read the group part, my apologies – Marco Apr 18 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.