SharePoint Framework - CRUD Operations Using No Framework

Overview

In the previous 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 the No Framework option. The CRUD operations will be performed using REST APIs. 

Create SPFx Solution

Step 1

Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-crud-no-framework  
Step 2

Navigate to the above-created directory.
  1. cd spfx-crud-no-framework  
Step 3

Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Step 4

Yeoman generator will present you with the wizard by asking questions about the solution to be created.

CRUD operations using No Framework 
 
Solution Name

Hit Enter to have the default name (spfx-crud-no-framework 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).
 
Location 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 a 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 - NoFrameworkCRUD.
 
Web part description

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

Selected choice - CRUD operations with no framework.
 
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.
 
Step 5

Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.

Step 6

Once the scaffolding process is completed, in the command prompt type the below command to open the solution in the code editor of your choice.
  1. code .  
Configure Property for List Name

SPFx solution by default has the 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 be performed.
 
Step 1

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

Step 2

Rename DescriptionFieldLabel to ListNameFieldLabel.
 
CRUD operations using No Framework 
  1. declare interface INoFrameworkCrudWebPartStrings {  
  2.   PropertyPaneDescription: string;  
  3.   BasicGroupName: string;  
  4.   ListNameFieldLabel: string;  
  5. }  
  6.   
  7. declare module 'NoFrameworkCrudWebPartStrings' {  
  8.   const strings: INoFrameworkCrudWebPartStrings;  
  9.   export = strings;  
  10. }  
Step 3

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

CRUD operations using No Framework  
  1. define([], function() {  
  2.   return {  
  3.     "PropertyPaneDescription""Description",  
  4.     "BasicGroupName""Group Name",  
  5.     "ListNameFieldLabel""List Name"  
  6.   }  
  7. });  
Step 4

Open main webpart file (NoFrameworkCrudWebPart.ts) under \src\webparts\noFrameworkCrud folder.

Step 5

Rename description property pane field to listName.

CRUD operations using No Framework 
  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 { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';  
  10. import { IListItem } from './IListItem';  
  11.   
  12. import styles from './NoFrameworkCrudWebPart.module.scss';  
  13. import * as strings from 'NoFrameworkCrudWebPartStrings';  
  14.   
  15. export interface INoFrameworkCrudWebPartProps {  
  16.   listName: string;  
  17. }  
  18.   
  19. export default class NoFrameworkCrudWebPart extends BaseClientSideWebPart<INoFrameworkCrudWebPartProps> {  
  20.   private listItemEntityTypeName: string = undefined;  
  21.   
  22.   public render(): void {  
  23.     this.domElement.innerHTML = `  
  24.       <div class="${ styles.noFrameworkCrud }">  
  25.         <div class="${ styles.container }">  
  26.           <div class="${ styles.row }">  
  27.             <div class="${ styles.column }">  
  28.               <span class="${ styles.title }">Welcome to SharePoint!</span>  
  29.               <p class="${ styles.subTitle }">Customize SharePoint experiences using Web Parts.</p>  
  30.               <p class="${ styles.description }">${escape(this.properties.listName)}</p>  
  31.           <a href="https://aka.ms/spfx" class="${ styles.button }">  
  32.                 <span class="${ styles.label }">Learn more</span>  
  33.               </a>  
  34.             </div>  
  35.           </div>  
  36.         </div>  
  37.       </div>`;  
  38.   }  
  39.   
  40.   protected get dataVersion(): Version {  
  41.     return Version.parse('1.0');  
  42.   }  
  43.   
  44.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  45.     return {  
  46.       pages: [  
  47.         {  
  48.           header: {  
  49.             description: strings.PropertyPaneDescription  
  50.           },  
  51.           groups: [  
  52.             {  
  53.               groupName: strings.BasicGroupName,  
  54.               groupFields: [  
  55.                 PropertyPaneTextField('listName', {  
  56.                   label: strings.ListNameFieldLabel  
  57.                 })  
  58.               ]  
  59.             }  
  60.           ]  
  61.         }  
  62.       ]  
  63.     };  
  64.   }  
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.

CRUD operations using No Framework 

Model for List Item

Let us add a class (IListItem.ts) representing the list item.
 
CRUD operations using No Framework 
  1. export interface IListItem {  
  2.     Title?: string;  
  3.     Id: number;  
  4. }  

Add Controls to WebPart

Step 1

Open main webpart file (NoFrameworkCrudWebPart.ts) under \src\webparts\noFrameworkCrud folder.

Step 2

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

CRUD operations using No Framework 
  1. export default class NoFrameworkCrudWebPart extends BaseClientSideWebPart<INoFrameworkCrudWebPartProps> {  
  2.   private listItemEntityTypeName: string = undefined;  
  3.   
  4.   public render(): void {  
  5.     this.domElement.innerHTML = `  
  6.       <div class="${ styles.noFrameworkCrud }">  
  7.         <div class="${ styles.container }">  
  8.           <div class="${ styles.row }">  
  9.             <div class="${ styles.column }">  
  10.               <span class="${ styles.title }">CRUD operations</span>  
  11.               <p class="${ styles.subTitle }">No Framework</p>  
  12.               <p class="${ styles.description }">Name: ${escape(this.properties.listName)}</p>  
  13.   
  14.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  15.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  16.                   <button class="${styles.button} create-Button">  
  17.                     <span class="${styles.label}">Create item</span>  
  18.                   </button>  
  19.                   <button class="${styles.button} read-Button">  
  20.                     <span class="${styles.label}">Read item</span>  
  21.                   </button>  
  22.                 </div>  
  23.               </div>  
  24.   
  25.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  26.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  27.                   <button class="${styles.button} update-Button">  
  28.                     <span class="${styles.label}">Update item</span>  
  29.                   </button>  
  30.                   <button class="${styles.button} delete-Button">  
  31.                     <span class="${styles.label}">Delete item</span>  
  32.                   </button>  
  33.                 </div>  
  34.               </div>  
  35.   
  36.               <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  37.                 <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
  38.                   <div class="status"></div>  
  39.                   <ul class="items"><ul>  
  40.                 </div>  
  41.               </div>  
  42.   
  43.             </div>  
  44.           </div>  
  45.         </div>  
  46.       </div>`;  
  47.   
  48.       this.setButtonsEventHandlers();  
  49.   }  
  50.   
  51.   private setButtonsEventHandlers(): void {  
  52.     const webPart: NoFrameworkCrudWebPart = this;  
  53.     this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.createItem(); });  
  54.     this.domElement.querySelector('button.read-Button').addEventListener('click', () => { webPart.readItem(); });  
  55.     this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); });  
  56.     this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.deleteItem(); });  
  57.   }  
  58.   
  59.   private createItem(): void {  
  60.   }  
  61.   
  62.   private readItem(): void {  
  63.   }  
  64.   
  65.   private updateItem(): void {  
  66.   }  
  67.   
  68.   private deleteItem(): void {  
  69.   }  
  70. }  
Step 3

In the command prompt type “gulp serve” to see the buttons on the webpart.
 
CRUD operations using No Framework 
 
Step 4

We will perform read, update, and delete operations on the latest item in the SharePoint list. Let us implement a generic method (getLatestItemId) which will return the id of latest item from a given list. We will use the REST API to query the list.
  1. private getLatestItemId(): Promise<number> {  
  2.   return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {  
  3.     this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items?$orderby=Id desc&$top=1&$select=id`,  
  4.       SPHttpClient.configurations.v1,  
  5.       {  
  6.         headers: {  
  7.           'Accept''application/json;odata=nometadata',  
  8.           'odata-version'''  
  9.         }  
  10.       })  
  11.       .then((response: SPHttpClientResponse): Promise<{ value: { Id: number }[] }> => {  
  12.         return response.json();  
  13.       }, (error: any): void => {  
  14.         reject(error);  
  15.       })  
  16.       .then((response: { value: { Id: number }[] }): void => {  
  17.         if (response.value.length === 0) {  
  18.           resolve(-1);  
  19.         }  
  20.         else {  
  21.           resolve(response.value[0].Id);  
  22.         }  
  23.       });  
  24.   });  
  25. }  

Implement Create Operation

First, start by implementing the Create method, which will add an item to SharePoint list.
  1. private createItem(): void {  
  2.   const body: string = JSON.stringify({  
  3.     'Title': `Item ${new Date()}`  
  4.   });  
  5.   
  6.   this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items`,  
  7.   SPHttpClient.configurations.v1,  
  8.   {  
  9.     headers: {  
  10.       'Accept''application/json;odata=nometadata',  
  11.       'Content-type''application/json;odata=nometadata',  
  12.       'odata-version'''  
  13.     },  
  14.     body: body  
  15.   })  
  16.   .then((response: SPHttpClientResponse): Promise<IListItem> => {  
  17.     return response.json();  
  18.   })  
  19.   .then((item: IListItem): void => {  
  20.     this.updateStatus(`Item '${item.Title}' (ID: ${item.Id}) successfully created`);  
  21.   }, (error: any): void => {  
  22.     this.updateStatus('Error while creating the item: ' + error);  
  23.   });  
  24. }  
  25.   
  26. private updateStatus(status: string, items: IListItem[] = []): void {  
  27.   this.domElement.querySelector('.status').innerHTML = status;  
  28.   this.updateItemsHtml(items);  
  29. }  
  30.   
  31. private updateItemsHtml(items: IListItem[]): void {  
  32.   this.domElement.querySelector('.items').innerHTML = items.map(item => `<li>${item.Title} (${item.Id})</li>`).join("");  
  33. }  
Implement Read Operation

We will use the REST API to read the latest item.
  1. private readItem(): void {  
  2.   this.getLatestItemId()  
  3.     .then((itemId: number): Promise<SPHttpClientResponse> => {  
  4.       if (itemId === -1) {  
  5.         throw new Error('No items found in the list');  
  6.       }  
  7.   
  8.       this.updateStatus(`Loading information about item ID: ${itemId}...`);  
  9.         
  10.       return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${itemId})?$select=Title,Id`,  
  11.         SPHttpClient.configurations.v1,  
  12.         {  
  13.           headers: {  
  14.             'Accept''application/json;odata=nometadata',  
  15.             'odata-version'''  
  16.           }  
  17.         });  
  18.     })  
  19.     .then((response: SPHttpClientResponse): Promise<IListItem> => {  
  20.       return response.json();  
  21.     })  
  22.     .then((item: IListItem): void => {  
  23.       this.updateStatus(`Item ID: ${item.Id}, Title: ${item.Title}`);  
  24.     }, (error: any): void => {  
  25.       this.updateStatus('Loading latest item failed with error: ' + error);  
  26.     });  
  27. }  
Implement Update Operation

Firstly, we will get the latest item and update it.
  1. private updateItem(): void {  
  2.   let latestItemId: number = undefined;  
  3.   this.updateStatus('Loading latest item...');  
  4.   
  5.   this.getLatestItemId()  
  6.     .then((itemId: number): Promise<SPHttpClientResponse> => {  
  7.       if (itemId === -1) {  
  8.         throw new Error('No items found in the list');  
  9.       }  
  10.   
  11.       latestItemId = itemId;  
  12.       this.updateStatus(`Loading information about item ID: ${itemId}...`);  
  13.         
  14.       return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${latestItemId})?$select=Title,Id`,  
  15.         SPHttpClient.configurations.v1,  
  16.         {  
  17.           headers: {  
  18.             'Accept''application/json;odata=nometadata',  
  19.             'odata-version'''  
  20.           }  
  21.         });  
  22.     })  
  23.     .then((response: SPHttpClientResponse): Promise<IListItem> => {  
  24.       return response.json();  
  25.     })  
  26.     .then((item: IListItem): void => {  
  27.       this.updateStatus(`Item ID1: ${item.Id}, Title: ${item.Title}`);  
  28.   
  29.       const body: string = JSON.stringify({  
  30.         'Title': `Updated Item ${new Date()}`  
  31.       });  
  32.   
  33.       this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${item.Id})`,  
  34.         SPHttpClient.configurations.v1,  
  35.         {  
  36.           headers: {  
  37.             'Accept''application/json;odata=nometadata',  
  38.             'Content-type''application/json;odata=nometadata',  
  39.             'odata-version''',  
  40.             'IF-MATCH''*',  
  41.             'X-HTTP-Method''MERGE'  
  42.           },  
  43.           body: body  
  44.         })  
  45.         .then((response: SPHttpClientResponse): void => {  
  46.           this.updateStatus(`Item with ID: ${latestItemId} successfully updated`);  
  47.         }, (error: any): void => {  
  48.           this.updateStatus(`Error updating item: ${error}`);  
  49.         });  
  50.     });  
  51. }  
Implement Delete Operation

REST APIs are used to find and delete the latest item.
  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<SPHttpClientResponse> => {  
  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 this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${latestItemId})?$select=Id`,  
  18.         SPHttpClient.configurations.v1,  
  19.         {  
  20.           headers: {  
  21.             'Accept''application/json;odata=nometadata',  
  22.             'odata-version'''  
  23.           }  
  24.         });  
  25.     })  
  26.     .then((response: SPHttpClientResponse): Promise<IListItem> => {  
  27.       etag = response.headers.get('ETag');  
  28.       return response.json();  
  29.     })  
  30.     .then((item: IListItem): Promise<SPHttpClientResponse> => {  
  31.       this.updateStatus(`Deleting item with ID: ${latestItemId}...`);  
  32.       return this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${item.Id})`,  
  33.         SPHttpClient.configurations.v1,  
  34.         {  
  35.           headers: {  
  36.             'Accept''application/json;odata=nometadata',  
  37.             'Content-type''application/json;odata=verbose',  
  38.             'odata-version''',  
  39.             'IF-MATCH': etag,  
  40.             'X-HTTP-Method''DELETE'  
  41.           }  
  42.         });  
  43.     })  
  44.     .then((response: SPHttpClientResponse): void => {  
  45.       this.updateStatus(`Item with ID: ${latestItemId} successfully deleted`);  
  46.     }, (error: any): void => {  
  47.       this.updateStatus(`Error deleting item: ${error}`);  
  48.     });  
  49. }  
Test the WebPart

Step 1

On the command prompt, type “gulp serve”.

Step 2

Open SharePoint site.

Step 3

Navigate to /_layouts/15/workbench.aspx.

Step 4

Add the webpart to the page.

Step 5

Edit webpart; in the Properties pane, type the list name.
 
CRUD operations using No Framework 
 
Step 6

Click the buttons (Create Item, Read Item, Update Item, and Delete Item) one by one to test the webpart.

Step 7

Verify the operations are taking place in the SharePoint list.
 

Create Operation

CRUD operations using No Framework
  
Read Operation
 
CRUD operations using No Framework 
 
Update Operation
 
CRUD operations using No Framework 
 
Delete Operation
 
CRUD operations using No Framework 

Troubleshooting

In some cases, the SharePoint workbench (https://[tenant].sharepoint.com/_layouts/15/workbench.aspx) shows this error even if the “gulp serve” is running.
 
CRUD operations using No Framework 
 
Open the below URL in the next tab of the browser. Accept the warning message.
https://localhost:4321/temp/manifests.js

Summary

SharePoint framework client web parts can be developed with No JavaScript options. REST APIs can be used to perform the CRUD operations on SharePoint list.