SPFX PnP JS

In our previous demo, 

https://tejasadventure.blogspot.com/2021/07/spfx-crud-operation-using-no-javascript.html

We observed how to implement CRUD operations using SPHttpClient library using no javascript framework (Using JQuery) and Rest Full services of Create, Read, Update, Delete and Read All Items.

Using SP REST full services using SPHttpClient - little bit coding is tricky. Microsoft has simplified the whole process using PnP Js.

Once we have handy in understanding the code, it is very easy to implement PnP js always for SPFX.

Let get started.

1. First we need to install "npm shrinkwrap"

It will ensure wrap, shirnk and lock our dependencies. Also the version of the depedencies. 

2. We need to save the PnP js using the below command for our webpart project.

npm install sp-pnp-js --save

3. first in code, we need to import sp pnp js.

import * as pnp from 'sp-pnp-js';

4. to add list item.


pnp.sp.web.lists.getByTitle('YourListname here').items.add({
    //pass here your JSON formatted body.
which means form values pass it to your sharepoint list columns.
})

example below.:

private addListItem():void {
    var softwaretitle = document.getElementById('txtSoftwareTitle')['value'];
    var softwarename = document.getElementById('txtSoftwareName')['value'];
    var softwareversion = document.getElementById('txtSoftwareVersion')['value'];
    var softwarevendor = document.getElementById('ddlSoftwareVendor')['value'];
    var softwareDescription = document.getElementById('txtSoftwareDescription')['value'];
    const siteurlstring = this.context.pageContext.site.absoluteUrl + "/_api/web/lists/getbytitle('SoftwareCatalog')/items";
    pnp.sp.web.lists.getByTitle("SoftwareCatalog").items.add({
      "Title":softwaretitle,
      "SoftwareVendor":softwarevendor,
      "SoftwareDescription":softwareDescription,
      "SoftwareName":softwarename,
      "SoftwareVersion":softwareversion
    }).then(r=>{
      alert("added successfully");
      this.clear();
    });
  }

5. Read a Single record using pnp JS.

We are passing the list Item ID and pass it to REST full service and fetch the item values.

let idstring = document.getElementById("txtID")["value"]; // grabbing the item ID
from a text box
//to PNP get list item, we are passing the ID and getting its values rendering to the DOM
pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).get().then((item:any)=>{
      document.getElementById("txtSoftwareTitle")["value"]=item.Title;
      document.getElementById("txtSoftwareName")["value"]=item.SoftwareName;
      document.getElementById("ddlSoftwareVendor")["value"]=item.SoftwareVendor;
      document.getElementById("txtSoftwareVersion")["value"]=item.SoftwareVersion;
      document.getElementById("txtSoftwareDescription")["value"]=item.SoftwareDescription;
    });

example code read item from SP List:
  private readListItem():void {
    let idnumber = document.getElementById("txtID")["value"];
    pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).get().then((item:any)=>{
      document.getElementById("txtSoftwareTitle")["value"]=item.Title;
      document.getElementById("txtSoftwareName")["value"]=item.SoftwareName;
      document.getElementById("ddlSoftwareVendor")["value"]=item.SoftwareVendor;
      document.getElementById("txtSoftwareVersion")["value"]=item.SoftwareVersion;
      document.getElementById("txtSoftwareDescription")["value"]=item.SoftwareDescription;
    });
  }

6. Update a Record in SharePoint List.

pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).update({
    //sp list columns and its values in JSON object format
})

example code
  private updateListItem():void {
    var softwaretitle = document.getElementById('txtSoftwareTitle')['value'];
    var softwarename = document.getElementById('txtSoftwareName')['value'];
    var softwareversion = document.getElementById('txtSoftwareVersion')['value'];
    var softwarevendor = document.getElementById('ddlSoftwareVendor')['value'];
    var softwareDescription = document.getElementById('txtSoftwareDescription')['value'];

    let idnumber = document.getElementById("txtID")['value'];

    const siteurlstring = this.context.pageContext.site.absoluteUrl + "/_api/web/lists/getbytitle('SoftwareCatalog')/items("+id+")";

    pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).update({
      "Title":softwaretitle,
      "SoftwareVendor":softwarevendor,
      "SoftwareDescription":softwareDescription,
      "SoftwareName":softwarename,
      "SoftwareVersion":softwareversion
    }).then(r=>{
      alert("Updated successfully");
      this.clear();
    });
  }

7. Read All items from SharePoint List.

pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.get()
here items.get() means getting all the items from the SoftwareCatalog SharePoint list.

Just observe for single record means
pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).get().then((item:any)=>{

getById - representing the single record.

Those difference should observe.

Code Example:

  private readAllItems():void{
    let htmlstring = '<table border="1" width="100%" style="border-collapse:collapse;">';
    html += '<th>ID</th><th>Title</th><th>Vendor</th><th>Description</th><th>Name</th><th>Version</th>';

    pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.get().then((items:any[])=>{
      items.forEach(function(item){
        html += `<tr>
        <td>${item.Id}</td> 
        <td>${item.Title}</td>
        <td>${item.SoftwareVendor}</td>
        <td>${item.SoftwareDescription}</td>
        <td>${item.SoftwareName}</td>
        <td>${item.SoftwareVersion}</td>
      </tr>`;
      });
      html += `</table>`;
      const allitems : Element = this.domElement.querySelector("#spListData");
      allitems.innerHTML = html;
    });
  }

7. Delete item from SharePoint List.

First grab the item ID which we want the item to get delete
let idnumber = document.getElementById("txtID")['value'];

now
pnp.sp.web.lists.getByTitle('SoftwareCatalog').items.getById(id).delete()

Check out the full code.

Comments