SharePoint Framework - CRUD Operations Using SP PNP JS

Overview

In the article Develop First Client Side Web Part, we developed a basic SharePoint client web part which can run independently without any interaction with SharePoint. In this article, we will explore how to interact with the SharePoint list for CRUD (Create, Read, Update, and Delete) operations using external JavaScript library called SP PNP JS. The CRUD operations will be performed using REST APIs.

Brief information about SP-PnP-JS

SP PnP JS are patterns and practices that the core JavaScript library offers. They are simplified common operations with SharePoint to help developers concentrate on business logic without worrying much about the underlying technical implementation. It contains fluent APIs to work with SharePoint REST APIs. Read more about it at here.

Create SPFx Solution

Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-crud-sppnpjs  
Navigate to the above-created directory.
  1. cd spfx-crud-sppnpjs  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman generator will present you with the wizard by asking questions about the solution to be created.

SharePoint Framework - CRUD operations using SP PNP JS 
 
Solution Name

Hit Enter to have a default name (spfx-crud-sppnpjs in this case) or type in any other name for your solution.

Selected choice - Hit enter
 
Target for component

Here, we can select the target environment where we are planning to deploy the client webpart; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).

Selected choice - SharePoint Online only (latest)
 
Place of files

We may choose to use the same folder or create a subfolder for our solution.

Selected choice - Same folder.
 
Deployment option

Selecting Y will allow the app to be deployed instantly to all sites and will be accessible everywhere.

Selected choice - N (install on each site explicitly)
 
Type of client-side component to create

We can choose to create client-side webpart or an extension. Choose the webpart option.

Selected choice - WebPart.
 
Web part name

Hit enter to select the default name or type in any other name.

Selected choice - SPPnPJSCRUD
 
Web part description

Hit enter to select the default description or type in any other value.

Selected choice - CRUD operations with SP PnP JS
 
Framework to use

Select any JavaScript framework to develop the component. Available choices are No JavaScript Framework, React, and Knockout.

Selected choice - No JavaScript Framework
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.

Once the scaffolding process is completed, lock down the version of project dependencies by running below command
  1. npm shrinkwrap  
In the command prompt type the below command to open the solution in code editor of your choice.
  1. code .  

Configure sp-pnp-js

In the command prompt, run the below command to install sp-pnp-js
  1. npm install sp-pnp-js --save  

Configure Property for List Name

SPFx solution by default has a description property created. Let us change the property to list name. We will use this property to configure the list name on which the CRUD operation is to perform.

Step 1

Open mystrings.d.ts under \src\webparts\spPnPjscrud\loc\ folder

Step 2

Rename DescriptionFieldLabel to ListNameFieldLabel

SharePoint Framework - CRUD operations using SP PNP JS 
  1. declare interface ISpPnPjscrudWebPartStrings {  
  2.   PropertyPaneDescription: string;  
  3.   BasicGroupName: string;  
  4.   DescriptionFieldLabel: string;  
  5. }  
  6.   
  7. declare module 'SpPnPjscrudWebPartStrings' {  
  8.   const strings: ISpPnPjscrudWebPartStrings;  
  9.   export = strings;  
  10. }  
Step 3

In en-us.js file under \src\webparts\spPnPjscrud\loc\ folder set the display name for listName property,

SharePoint Framework - CRUD operations using SP PNP JS  
  1. define([], function() {  
  2.   return {  
  3.     "PropertyPaneDescription""Description",  
  4.     "BasicGroupName""Group Name",  
  5.     "DescriptionFieldLabel""Description Field"  
  6.   }  
  7. });   
Step 4

Open main webpart file (SpPnPjscrudWebPart.ts) under \src\webparts\spPnPjscrud folder.

Step 5

Rename description property pane field to listName

SharePoint Framework - CRUD operations using SP PNP JS  
  1. import { Version } from '@microsoft/sp-core-library';  
  2. import {  
  3.   BaseClientSideWebPart,  
  4.   IPropertyPaneConfiguration,  
  5.   PropertyPaneTextField  
  6. } from '@microsoft/sp-webpart-base';  
  7. import { escape } from '@microsoft/sp-lodash-subset';  
  8.   
  9. import styles from './SpPnPjscrudWebPart.module.scss';  
  10. import * as strings from 'SpPnPjscrudWebPartStrings';  
  11.   
  12. export interface ISpPnPjscrudWebPartProps {  
  13.   description: string;  
  14. }  
  15.   
  16. export default class SpPnPjscrudWebPart extends BaseClientSideWebPart<ISpPnPjscrudWebPartProps> {  
  17.   
  18.   public render(): void {  
  19.     this.domElement.innerHTML = `  
  20.       <div class="${ styles.spPnPjscrud }">  
  21.         <div class="${ styles.container }">  
  22.           <div class="${ styles.row }">  
  23.             <div class="${ styles.column }">  
  24.               <span class="${ styles.title }">Welcome to SharePoint!</span>  
  25.               <p class="${ styles.subTitle }">Customize SharePoint experiences using Web Parts.</p>  
  26.               <p class="${ styles.description }">${escape(this.properties.description)}</p>  
  27.               <a href="https://aka.ms/spfx" class="${ styles.button }">  
  28.                 <span class="${ styles.label }">Learn more</span>  
  29.               </a>  
  30.             </div>  
  31.           </div>  
  32.         </div>  
  33.       </div>`;  
  34.   }  
  35.   
  36.   protected get dataVersion(): Version {  
  37.     return Version.parse('1.0');  
  38.   }  
  39.   
  40.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  41.     return {  
  42.       pages: [  
  43.         {  
  44.           header: {  
  45.             description: strings.PropertyPaneDescription  
  46.           },  
  47.           groups: [  
  48.             {  
  49.               groupName: strings.BasicGroupName,  
  50.               groupFields: [  
  51.                 PropertyPaneTextField('description', {  
  52.                   label: strings.DescriptionFieldLabel  
  53.                 })  
  54.               ]  
  55.             }  
  56.           ]  
  57.         }  
  58.       ]  
  59.     };  
  60.   }  
  61. }  
Step 6

In the command prompt, type “gulp serve”

Step 7

In the SharePoint local workbench page, add the web part.

Step 8

Edit the web part to ensure the listName property pane field is getting reflected.

SharePoint Framework - CRUD operations using SP PNP JS 
 
Model for List Item

Add a class (IListItem.ts) representing the list item.

SharePoint Framework - CRUD operations using SP PNP JS 
  1. export interface IListItem {  
  2.     Title?: string;  
  3.     Id: number;  
  4. }  
  5.     

Add Controls to WebPart

Step 1

Open main webpart file (SpPnPjscrudWebPart.ts) under \src\webparts\spPnPjscrud folder.

Step 2

Modify Render method to include buttons for CRUD operations and add event handlers to each of the button

SharePoint Framework - CRUD operations using SP PNP JS  
  1. export default class SpPnPjscrudWebPart extends BaseClientSideWebPart<ISpPnPjscrudWebPartProps> {  
  2.   
  3.   public render(): void {  
  4.     this.domElement.innerHTML = `  
  5.       <div class="${ styles.spPnPjscrud }">  
  6.         <div class="${ styles.container }">  
  7.           <div class="${ styles.row }">  
  8.             <div class="${ styles.column }">  
  9.               <span class="${ styles.title }">CRUD operations</span>  
  10.               <p class="${ styles.subTitle }">SP PnP JS</p>  
  11.               <p class="${ styles.description }">Name: ${escape(this.properties.listName)}</p>  
  12.   
  13.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  14.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  15.                   <button class="${styles.button} create-Button">  
  16.                     <span class="${styles.label}">Create item</span>  
  17.                   </button>  
  18.                   <button class="${styles.button} read-Button">  
  19.                     <span class="${styles.label}">Read item</span>  
  20.                   </button>  
  21.                 </div>  
  22.               </div>  
  23.   
  24.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  25.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  26.                   <button class="${styles.button} update-Button">  
  27.                     <span class="${styles.label}">Update item</span>  
  28.                   </button>  
  29.                   <button class="${styles.button} delete-Button">  
  30.                     <span class="${styles.label}">Delete item</span>  
  31.                   </button>  
  32.                 </div>  
  33.               </div>  
  34.   
  35.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  36.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  37.                   <div class="status"></div>  
  38.                   <ul class="items"><ul>  
  39.                 </div>  
  40.               </div>                
  41.   
  42.             </div>  
  43.           </div>  
  44.         </div>  
  45.       </div>`;  
  46.   
  47.       this.setButtonsEventHandlers();  
  48.   }  
  49.   
  50.   private setButtonsEventHandlers(): void {  
  51.     const webPart: SpPnPjscrudWebPart = this;  
  52.     this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.createItem(); });  
  53.     this.domElement.querySelector('button.read-Button').addEventListener('click', () => { webPart.readItem(); });  
  54.     this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); });  
  55.     this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.deleteItem(); });  
  56.   }  
  57.   
  58.   private updateItemsHtml(items: IListItem[]): void {  
  59.   }  
  60.   
  61.   private readItem(): void {  
  62.   }  
  63.   
  64.   private updateItem(): void {  
  65.   }  
  66.   
  67.   private deleteItem(): void {  
  68.   }  
  69.   
  70.   protected get dataVersion(): Version {  
  71.     return Version.parse('1.0');  
  72.   }  
  73.   
  74.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  75.     return {  
  76.       pages: [  
  77.         {  
  78.           header: {  
  79.             description: strings.PropertyPaneDescription  
  80.           },  
  81.           groups: [  
  82.             {  
  83.               groupName: strings.BasicGroupName,  
  84.               groupFields: [  
  85.                 PropertyPaneTextField('listName', {  
  86.                   label: strings.ListNameFieldLabel  
  87.                 })  
  88.               ]  
  89.             }  
  90.           ]  
  91.         }  
  92.       ]  
  93.     };  
  94.   }  
  95. }  
Step 3

In the command prompt type “gulp serve” to see the buttons on the webpart.
 
SharePoint Framework - CRUD operations using SP PNP JS 
 
Step 4

We will use the sp-pnp-js APIs to perform CRUD operations. Let us implement generic method which will return the id of latest item from given list using sp-pnp-js APIs. 
  1. private getLatestItemId(): Promise<number> {  
  2.   return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {  
  3.     sp.web.lists.getByTitle(this.properties.listName)  
  4.       .items.orderBy('Id'false).top(1).select('Id').get()  
  5.       .then((items: { Id: number }[]): void => {  
  6.         if (items.length === 0) {  
  7.           resolve(-1);  
  8.         }  
  9.         else {  
  10.           resolve(items[0].Id);  
  11.         }  
  12.       }, (error: any): void => {  
  13.         reject(error);  
  14.       });  
  15.   });  
  16. }  
Import sp-pnp-js

Add below import statements to main web part (SpPnPcrudWebPart.ts).
  1. import { IListItem } from './IListItem';  
  2. import pnp, { sp, Item, ItemAddResult, ItemUpdateResult } from "sp-pnp-js";  

Implement Create Operation

We will use the sp-pnp-js API of items.add to add the item to list
  1. private createItem(): void {  
  2.     this.updateStatus('Creating item...');  
  3.   
  4.     sp.web.lists.getByTitle(this.properties.listName).items.add({  
  5.       'Title': `Item ${new Date()}`  
  6.     }).then((result: ItemAddResult): void => {  
  7.       const item: IListItem = result.data as IListItem;  
  8.       this.updateStatus(`Item '${item.Title}' (ID: ${item.Id}) successfully created`);  
  9.     }, (error: any): void => {  
  10.       this.updateStatus('Error while creating the item: ' + error);  
  11.     });  
  12.     

Implement Read Operation

We will use sp-pnp-js API - getById to read the item.
  1. private readItem(): void {  
  2.     this.updateStatus('Reading latest items...');  
  3.   
  4.     this.getLatestItemId()  
  5.       .then((itemId: number): Promise<IListItem> => {  
  6.         if (itemId === -1) {  
  7.           throw new Error('No items found in the list');  
  8.         }  
  9.   
  10.         this.updateStatus(`Loading information about item ID: ${itemId}...`);  
  11.         return sp.web.lists.getByTitle(this.properties.listName)  
  12.           .items.getById(itemId).select('Title''Id').get();  
  13.       })  
  14.       .then((item: IListItem): void => {  
  15.         this.updateStatus(`Item ID: ${item.Id}, Title: ${item.Title}`);  
  16.       }, (error: any): void => {  
  17.         this.updateStatus('Loading latest item failed with error: ' + error);  
  18.       });  
  19.   }  

Implement Update Operation

We will use sp-pnp-js API - update
  1. private updateItem(): void {  
  2.     this.updateStatus('Loading latest items...');  
  3.     let latestItemId: number = undefined;  
  4.     let etag: string = undefined;  
  5.   
  6.     this.getLatestItemId()  
  7.       .then((itemId: number): Promise<Item> => {  
  8.         if (itemId === -1) {  
  9.           throw new Error('No items found in the list');  
  10.         }  
  11.   
  12.         latestItemId = itemId;  
  13.         this.updateStatus(`Loading information about item ID: ${itemId}...`);  
  14.         return sp.web.lists.getByTitle(this.properties.listName)  
  15.           .items.getById(itemId).get(undefined, {  
  16.             headers: {  
  17.               'Accept''application/json;odata=minimalmetadata'  
  18.             }  
  19.           });  
  20.       })  
  21.       .then((item: Item): Promise<IListItem> => {  
  22.         etag = item["odata.etag"];  
  23.         return Promise.resolve((item as any) as IListItem);  
  24.       })  
  25.       .then((item: IListItem): Promise<ItemUpdateResult> => {  
  26.         return sp.web.lists.getByTitle(this.properties.listName)  
  27.           .items.getById(item.Id).update({  
  28.             'Title': `Updated Item ${new Date()}`  
  29.           }, etag);  
  30.       })  
  31.       .then((result: ItemUpdateResult): void => {  
  32.         this.updateStatus(`Item with ID: ${latestItemId} successfully updated`);  
  33.       }, (error: any): void => {  
  34.         this.updateStatus('Loading latest item failed with error: ' + error);  
  35.       });  
  36.   }  

Implement Delete Operation

We will use sp-pnp-js API - delete
  1. private deleteItem(): void {  
  2.   if (!window.confirm('Are you sure you want to delete the latest item?')) {  
  3.     return;  
  4.   }  
  5.   
  6.   this.updateStatus('Loading latest items...');  
  7.   let latestItemId: number = undefined;  
  8.   let etag: string = undefined;  
  9.   this.getLatestItemId()  
  10.     .then((itemId: number): Promise<Item> => {  
  11.       if (itemId === -1) {  
  12.         throw new Error('No items found in the list');  
  13.       }  
  14.   
  15.       latestItemId = itemId;  
  16.       this.updateStatus(`Loading information about item ID: ${latestItemId}...`);  
  17.       return sp.web.lists.getByTitle(this.properties.listName)  
  18.         .items.getById(latestItemId).select('Id').get(undefined, {  
  19.           headers: {  
  20.             'Accept''application/json;odata=minimalmetadata'  
  21.           }  
  22.         });  
  23.     })  
  24.     .then((item: Item): Promise<IListItem> => {  
  25.       etag = item["odata.etag"];  
  26.       return Promise.resolve((item as any) as IListItem);  
  27.     })  
  28.     .then((item: IListItem): Promise<void> => {  
  29.       this.updateStatus(`Deleting item with ID: ${latestItemId}...`);  
  30.       return sp.web.lists.getByTitle(this.properties.listName)  
  31.         .items.getById(item.Id).delete(etag);  
  32.     })  
  33.     .then((): void => {  
  34.       this.updateStatus(`Item with ID: ${latestItemId} successfully deleted`);  
  35.     }, (error: any): void => {  
  36.       this.updateStatus(`Error deleting item: ${error}`);  
  37.     });  
  38. }  
Test the WebPart
  1. On the command prompt, type “gulp serve”
  2. Open SharePoint site
  3. Navigate to /_layouts/15/workbench.aspx
  4. Add the webpart to page.
  5. Edit webpart, in the properties pane type the list name
  6. Click the buttons (Create Item, Read Item, Update Item, and Delete Item) one by one to test the webpart
  7. Verify the operations are taking place in SharePoint list.
Create Operation

SharePoint Framework - CRUD operations using SP PNP JS

Read Operation

SharePoint Framework - CRUD operations using SP PNP JS
 
Update Operation

SharePoint Framework - CRUD operations using SP PNP JS
 
Delete Operation

SharePoint Framework - CRUD operations using SP PNP JS

Troubleshooting

In some cases SharePoint workbench (https://[tenant].sharepoint.com/_layouts/15/workbench.aspx) shows the below error although “gulp serve” is running.
 
SharePoint Framework - CRUD operations using SP PNP JS 
 
Open below url in the next tab of browser. Accept the warning message.

https://localhost:4321/temp/manifests.js

Summary

sp-pnp-js APIs helps to perform common operations (like CRUD) with SharePoint easily. It makes the code easier to maintain. Developers can concentrate on business logic rather than worrying about the identifying and using various REST APIs to use in the code.