1

I am writing an SPFx, I have used React, PnP JS. I created a service class, which will be responsible to communicate with SharePoint. Below is the snippet of the code:

export class service implements ICrudService {
getListName: string;
private _listItems: IListItems[] = [];

constructor( context: WebPartContext, listName: string) {
    this.getListName = listName;
     sp.setup({ //this is line 1
        spfxContext: context, //this is line 2

     });// this is line 3

}
async UpdateDataToList(_items: IListItems) {
    let items: any[] = [];
    this.GetDataById(_items.ID).then((i) => {
        items = i;

    })
}

Previously, I was passing my web part context in the service constructor, and the code seems to be working fine.

const [_service] = React.useState(new service(props.context, props.listName));

I remove the context from service above, (//this is line 1 to this is line 3) and modified my service call accordingly,

const [_service] = React.useState(new service(props.listName));

Strangely, this code is still working fine and I am able to do the CRUD operations.

My question is, what is the use of WebPartContext?Why do I care about it? can I omit it? Or If I use REST API, then only I need the context?

Please Clarify.

1 Answer 1

0

As the name suggests, WebPartContext is the web part context object. This object contains the contextual services available to a web part. e.g. a contextual instance to the HTTP client.

So, you will pass WebPartContext to your service or React components only when you need to access some properties from actual web part context (Or SharePoint page context).

For Example:

  1. You want to access the URL of the current site.
  2. You would need to use a WebPartContext to call an external API using HttpClient class available with this object. This class provides methods to make GET and POST methods to any API.

However, some SharePoint experts suggests don't pass the whole web part context to your React components or Services and only pass few context properties, like the HTTP clients or the URL of the current site as you need them.

Source: Don't pass the whole web part context into your React components

Additional References:

  1. WebPartContext class
  2. SPFx – scoped context services
2
  • So, you will pass WebPartContext to your service or React components only when you need to access some properties from actual web part context (Or SharePoint page context). Thumbs up for this line. So Sharepoint Page context is same as web part context ?
    – Moranis
    Commented Jun 26, 2020 at 6:42
  • You can get access to the SP page context from web part context. Check this and this for more clarification. Commented Jun 26, 2020 at 6:49

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.