3

in my react component i use msgraph but i get the message "cannot read property 'context' of undefined" My code:

this.context.msGraphClientFactory
        .getClient()
        .then((client: MSGraphClient): void => {        
          client
            .api('/me')
            .get((error, response: any, rawResponse?: any) => {
            console.log(response);
            });
        })

I tried to pass the context from my webpart to the component but then i get the error "Cannot read property 'context' of undefined"

Any idea? Thanks

1 Answer 1

6

This is because the msGraphClientFactory is an object on the SPFx web part context and not the react component context.

You will need to pass the msGraphClientFactory object explicitly as a property to the React component.

In your SPFx webpart:

public render(): void {
    const element: React.ReactElement<ICustomWebPartProps> = React.createElement(
      CustomWebPart,
      {
        msGraphClientFactory: this.context.msGraphClientFactory,
      }
    );

    ReactDom.render(element, this.domElement);
  }

And then in your React component, you can reference that from the current component props object:

this.props.msGraphClientFactory
        .getClient()
        .then((client: MSGraphClient): void => {        
          client
            .api('/me')
            .get((error, response: any, rawResponse?: any) => {
            console.log(response);
            });
        })
1
  • Thanks for the answer, it resolved my issue. Any reason why we have to explicitly pass this ?
    – nbi
    Commented Jul 21, 2020 at 13:40

Your Answer

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

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