4

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

1 Answer 1

6

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
    });
  });
}
5
  • I think I tried this in the tsx file. I'll try this in the ts file instead Nov 3, 2018 at 19:59
  • Any idea why it's the ts file and not the tsx? Nov 3, 2018 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. Nov 3, 2018 at 20:24
  • I have now tested this and it works perfectly. Thank you Nov 5, 2018 at 8:16
  • Check this link - sharepointndme.wordpress.com/2019/03/09/… Mar 9, 2019 at 8:57

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.