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
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 Nov 3, 2018 at 19:59
-
-
2The 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
-
-