3

How can I get the sharepoint groups the current user is a part/ belogns to, without @pnp/sp js framework in SPFx ?

2 Answers 2

4

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:

    const queryUrl = `${this.context.pageContext.site.absoluteUrl}/_api/web/currentuser/groups`;
    const siteGroupsData = await this.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1);
    const siteGroups = (await siteGroupsData.json()).value;
    siteGroups.forEach((siteGroup) => console.log(siteGroup));   
13
  • getting error in "context"
    – user10000
    Apr 18, 2019 at 14:52
  • Cannot read property 'get' of undefined
    – user10000
    Apr 18, 2019 at 14:52
  • i wrote this method inside the render method of <webpartname>.ts file Apr 18, 2019 at 14:54
  • I wrote it there only.
    – user10000
    Apr 18, 2019 at 15:00
  • public render(): React.ReactElement<IReactGetItemsProps> {
    – user10000
    Apr 18, 2019 at 15:00
0

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

2
  • 1
    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. Apr 18, 2019 at 16:56
  • you're right i didn't read the group part, my apologies
    – Marco
    Apr 18, 2019 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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