Search code examples
typescriptsharepoint-onlinespfx

Getting data for an SPFx web part? No data being returned even though it's being output to the console


I am creating an SPFx webpart for SharePoint Online. I use this code. It does write values to the console (all the email addresses of the people in the group) but it doesn't return the 'stringToReturn' value to display in the web part.

My web part displays: Meet the Team... undefined

Am I doing something fundamentally wrong?

Thanks P

public async render(): Promise<void> {

    
      this.domElement.innerHTML = `
      <section>
        <div>
          Meet the Team...
        </div>
        
        <div>
        ${await this.getGroupData()}
        </div>
      </section>`;
    }

protected async getGroupData(): Promise<string>
  {
    let stringToReturn:string;


    try
    {
    this.context.msGraphClientFactory.getClient('3')
    .then((client: MSGraphClientV3): void => {
      client.api('groups/<GUID>/members')
      .get((error: any, response: any, rawResponse?: any) => {

          const members: MicrosoftGraph.User[] = response.value;

          for (const memberDetail of members){
            console.log('memberDetail.mail:' + memberDetail.mail);
            stringToReturn = memberDetail.mail + "<br>";
          }

        });
    });

    }catch(e){
      
      stringToReturn = e.message.toString();

    }

Solution

  • You are not returning the Promise.

    Either you go with the async await style

        var client = await this.context.msGraphClientFactory.getClient('3');
        var result = await client.api(...).get();
        //do something with the result here
        return stringToReturn;
    

    Or you can do something like

    return new Promise((resolve) => {
        this.context.msGraphClientFactory.getClient('3')
        .then((client: MSGraphClientV3): void => {
          client.api('groups/<GUID>/members')
          .get((error: any, response: any, rawResponse?: any) => {
    
              const members: MicrosoftGraph.User[] = response.value;
    
              for (const memberDetail of members){
                console.log('memberDetail.mail:' + memberDetail.mail);
                stringToReturn = memberDetail.mail + "<br>";
              }
              //when your string is ready return by resolving it
              resolve(stringToReturn);
            });
        });
     });