3

I'm having trouble getting the correct site context for @pnp/sp. It works fine in workbench but not when I deploy to a site and add to a modern page. My api calls are being made to /_api/sitepages and not the root web. Am I missing something? I'm using the react spfx yeoman template

4

You need to initialize the pnp library with the SPFx context.

For that you need to add the below code in your webpart's .ts (TypeScript) file:

1) Add the below import statement

import pnp from "sp-pnp-js";

2) Add/Update the onInit method:

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    pnp.setup({
      spfxContext: this.context
    });

  });
}

If however, you are using the newer pnp js (@pnp/sp) scoped libraries, you need to add the below code in the webpart's .ts (TypeScript) file:

1) Add the below import statement

import { sp } from "@pnp/sp";

2) Add/Update the onInit method:

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    // other init code may be present

    sp.setup({
      spfxContext: this.context
    });
  });
}
  • I think I tried this in the tsx file. I'll try this in the ts file instead – chris rowles Nov 3 '18 at 19:59
  • Any idea why it's the ts file and not the tsx? – chris rowles Nov 3 '18 at 20:18
  • 2
    The oninit method is the first method called even before render method. In the oninit method, we initialise and pass the context to PNP. This ensures that the code works correctly. If we do that in tsx file, it will be after render method call which will be problematic. – Gautam Sheth Nov 3 '18 at 20:24
  • I have now tested this and it works perfectly. Thank you – chris rowles Nov 5 '18 at 8:16
  • Check this link - sharepointndme.wordpress.com/2019/03/09/… – Harsha Vardhini Mar 9 at 8:57

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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