reactjssharepointspfxpnp-js

Retrieve ID after pushing to SharePoint list using React PNPJs


I'm building a SharePoint SPFx react app. In a nutshell, the user fills out a form that I created. When the user hit's submit, using PNPJs: https://pnp.github.io/pnpjs/sp/items/ I'm adding the item to a list called Request.

From there I want to send an email that contains the URL link to that item they created. Right now, my code adds the item to the list and I'm able to send an email with no problem. However, I want to get the ID of the item that was just added to the list, so that I can add it to the email.

Here is a striped down snippet of my function that adds items to the Request list.

async submitNewRequest():Promise<any> {

    let preprocessedData;

    try {       

        // add an item to the list
        pnp.sp.web.lists.getByTitle("Requests").items.add({
            Title: this.state.Title,
            Requestor_x0020_Email: this.state.getEmail,
            Created: this.state.startDate,

        }).then((iar) => {
            console.log(iar);
            //Is this where I would get the ID 
        }); 
            
        const emailProps: EmailProperties = {
            To: [this.state.getEmail],
            Subject: "Your court requisition has been submitted.",
            Body: this.initalMessage
        };
        
    } catch(error) {

    }

    return preprocessedData;            


}

I believe what I have to do is in the .then((iar) => { when item is successfully added to the list, to get a response back with that item ID. But I'm not sure how. In my const emailProps: EmailProperties is where I'm sending the email, which again works.

Typically I can do something like this await sp.web.lists.getByTitle("Request").items.getById(1).get(); and in the console I will get back something like this:

0:
Title: "My title here"
Description: "Description Here"
ID: 24

Here is on submit function:

async _onNewRequest(event) {
    event.preventDefault();
    await this.submitNewRequest();
    this.displayPop();
}   

And lastly my email function:

get initalMessage() {
    return `<p>This is my email template that I stripped down.</p>
    
    &nbsp;
    <p>
    <a href="https://mywebsite.sharepoint.com/sites/Requests/SitePages/Home.aspx#/MyRequests/'+ NEED_ID_HERE +'" target="_blank">
        Click Here
    </a>
</p>`; 

Solution

  • You could retrieve the Id of the item like this:

      sp.web.lists.getByTitle("ct0").items.add({
        Title:"test"
      }).then(iar=>{
        console.log(iar.data.ID);
      })
    

    The code would be like this:

      const iar=await sp.web.lists.getByTitle("ct0").items.add({
        Title:"test"
      });
      const id=iar.data.ID;
      const emailProps: EmailProperties = {
            To: [this.state.getEmail],
            Subject: "Your court requisition has been submitted.",
            Body: this.initalMessage,
            ID:id
      };