1

I have deployed a web part to a site collection (where the web part is designed to go) and I am getting errors for 3 particular features on the form. I am using sp.web for these features.

  1. I have created a 'Hello User' which uses this function:
public _getUser() { 
    sp.web.currentUser.get().then((user) => {

      this.setState({
        CurrentUserTitle: user.Title,
        FullName: user.Title,
        CurrentUser: user.LoginName,
        CurrentUserID: user.Id,
        CurrentUserEmail: user.Email,

      }

  1. A Departments list drop down which populates with an SP list.
public _getDepartments() {
  sp.web.lists.getByTitle("Departments").items.get().then((items: any[]) => {
    let returnedDepts: IDropdownOption[] = items.map((item) => { return { key: item.Title, text: item.Title }; });
    this.setState({ DepartmentsList: returnedDepts });
  });
}

  1. A Submit button. The function:
private _onSubmit() {

      sp.web.lists.getByTitle('Data and Report Form').items.add({

        FullName: this.state.FullName,
        UniId: this.state.UniId,
        Email: this.state.UserEmail,
        Phone: this.state.PhoneNo,
        Department: this.state.SelectedDept,
        SubDepartment: this.state.SubDepartment,
        StartDate: this.state.StartDate,
        DiscoveryDate: this.state.DateOfDiscovery,
        Details: this.state.IncidentDetails,
        PersonalData: this.state.PersonalData

      }).then((iar: ItemAddResult) => {
        console.log(iar);
        let list = sp.web.lists.getByTitle('Data and Report Form');
        list.items.getById(iar.data.Id).update({
            Title: 'DIBR'+iar.data.Id, 
        });
        this.setState({
          JobRef: iar.data.Id,
        });
      });
    }


The form works perfectly in non-local SharePoint workbench served on the actual site it's meant to be deployed on. When deployed as a package to the site itself and added as a web part it now shows these errors:

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (Fetch)GET - https://myDomain.sharepoint.com/sites/IncidentReporting/SitePages/_api/web/currentuser

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (Fetch)GET - https://myDomain.sharepoint.com/sites/IncidentReporting/SitePages/_api/web/lists/getByTitle('Departments')/items

I get a similar message when trying to submit. A I said, these all work on the non-local workbench.

Additional details:

If I add the webpart to the homepage of the modern site as a web part I get these error (different to the ones if I add the webpart to a page):

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (Fetch)GET - https://MyDomain.sharepoint.com/sites/_api/web/lists/getByTitle('Departments')/items

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (Fetch)GET - https://MyDomain.sharepoint.com/sites/_api/web/currentuser

as you can see it's missing the actual site in the URL. Why the difference?

Has anyone got an idea why it's behaving differently when deployed? And why is it showing a different error if I place the web part on different areas of the site collection.

Update: I've attempted to use this:

import pnp from "sp-pnp-js";



public onInit(): Promise<void> {

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

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

  });
}

But I don't know how to implement it as onInit is Angular isn't it?

HELP!

T

NightTom
  • 418
  • 15
  • 37

2 Answers2

1

Figured it out.....

MAKE SURE TO PUT:

https://github.com/SharePoint/PnP-JS-Core/wiki/Using-sp-pnp-js-in-SharePoint-Framework

import pnp from "sp-pnp-js";

// ...

public onInit(): Promise {

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

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

}); In your root .ts file!!!!!

This had me for days!

NightTom
  • 418
  • 15
  • 37
1

This issue occurs because the PnP JS API didn’t get the SharePoint context. It is taking the SITEURL + '/SitePages' to get the context. So, what you need to do is that in the props file, add a new 'siteUrl' property.

export interface IDemoWebPartProps{  
  description: string;  
  siteUrl: string;  
}  

and then in the Webpart.ts file, initialize this property with this value.

public render(): void {  
    const element: React.ReactElement<IDemoWebPartProps> = React.createElement(  
      Demo,  
      {  
        description: this.properties.description,  
        siteUrl: this.context.pageContext.web.absoluteUrl  
      }  
    );

Finally, In the .tsx file initialize the Web parameter using this property.

let web = new Web(this.props.siteUrl);

and use this to get the data from required lists using pnp-js.

  • Hmm, isn't public onInit(): Promise { return super.onInit().then(_ => { // other init code may be present pnpSetup({ spfxContext: this.context }); }); } put in the webpart.ts file enough? – NightTom Dec 04 '19 at 15:53
  • Also how would you use web in the sp.web.lists ?? – NightTom Dec 04 '19 at 15:55
  • 1
    Yeah, the OnInit method should work fine. But the main purpose why this error occurs is that the url from which it's finding the context is not right. So fixing the url would do the job. Also, it's not recommended to define the whole context in the webpart.ts file bcoz it'll impact the performance. Best way is to explicitly load the context parts. – Sahil Jhamb Dec 05 '19 at 19:06
  • 1
    I used the web like by removing the 'sp' part. Example - web.lists.getListbytitle('x')... try this out it'll work. – Sahil Jhamb Dec 05 '19 at 19:07
  • So inserting the public onInit() method above in my comment reduces performance? – NightTom Dec 06 '19 at 08:59