Working with list items with Typescript and REST API – SPfx

Total visits : 2153

The Modern SharePoint Framework Client Side WebPart’s using Typescript and react. Here I am going to show in this article how to perform basic create, read, update, and delete list item operations with the SharePoint REST interface and Typescript.

if you are new to SharePoint Framework Web part, follow the prerequisites first…

Prerequisites

  1. Setup SharePoint Tenant
    • Example : https://jenkinsblogs.sharepoint.com/sites/dev
  2. Setup your machine
  3. First Webpart

The Add List Item output look like below

Note: Always upgrade to latest nodejs LTS version and make sure npm is up to date. In this example I am using

nodejs v6.10.3
npm v5.0.0
SharePoint Generator v1.0.2

Follow below steps to develop a list item operations

Step 1: Create a new Solution Example: spfxlistoperations

  • Go to run –> cmd and change folder to where you want to create a  new project
  • Create new folder md spfxlistoperations
  • change to new folder cd spfxlistoperations

Step 2: Create a new Webpart

  • type yo @microsoft/sharepoint and enter
  • It will create a new SharePoint Framework Solution
  • give new webpart name : spfxaddlistItem
  • then open visual studio code editor to start the development
  • to open visual studio code type code .

Step 3 : Below how to create a spfx web part to add list item

Open the project in visual studio code editor and open SpfxaddlistItemWebPart.ts file under src\webparts. Then import @microsoft/sp-http to refer SPHttpClient object.

import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';

Then design the user interface, I have added two fields Title, Description textbox and one button to submit the values to SharePoint list for this example. Also create one SharePoint list named spfxlist with two fields Title and Description.

Then add event listener to understand the click event

const events: SpfxaddlistItemWebPart = this;
var button = document.querySelector('#btn_add');
button.addEventListener('click', () => { events.CreateNewItem(); });

Step 4: Validate the control

Here I validated the the text boxes empty or not. Then get all values as array string.if user entered both title and description I have call the addIistItem function to create List Item.

private CreateNewItem(): void {
this.usermessage('Creating list Item ...');
lettitle= (<HTMLInputElement>document.getElementById("Title")).value.trim();
letdescription= (<HTMLInputElement>document.getElementById("description")).value.trim();
if(title!=''&&description!='')
{
//Create a array object with all column values
letrequestdata= {};
requestdata['Title'] =title;
requestdata['Description'] =description;
this.usermessage('Creating list Item ...'+requestdata);
this.addListItem('spfxlist',requestdata);
}
else
{
if(title==''&&description=='')
{this.usermessage('Please enter title and description');}
elseif(title=='')
{this.usermessage('Please enter title');}
elseif(description=='')
{this.usermessage('Please enter description');}
}
}

Step 5: Add/Create List Item using REST and Typescript

To do this operation, you must know the List Item entity and  properties of the list and pass that as the value of type in the HTTP request body.

To get the current URL using this.context.pageContext.web.absoluteUrl and I have hardcoded the list name you can get the list name from propery pane also, how to get the list name from property pane refer this post

  1. addListItem function to create Item in the spfxlist
  2. getListItemType function to get the list type using the List name dynamically, we can reuse this functions.
  3. usermessage function to show the status every time.
private addListItem(listname:string,requestdata:{})
 { 
 let requestdatastr = JSON.stringify(requestdata);
 requestdatastr = requestdatastr.substring(1, requestdatastr .length-1);
 console.log(requestdatastr);
 let requestlistItem: string = JSON.stringify({
 '__metadata': {'type': this.getListItemType(listname)}
 });
 requestlistItem = requestlistItem.substring(1, requestlistItem .length-1);
 requestlistItem = '{' + requestlistItem + ',' + requestdatastr + '}';
 console.log(requestlistItem);
 this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listname}')/items`,
 SPHttpClient.configurations.v1,
 {
 headers: {
 'Accept': 'application/json;odata=nometadata',
 'Content-type': 'application/json;odata=verbose',
 'odata-version': ''
 },
 body: requestlistItem
 })
 .then((response: SPHttpClientResponse): Promise<IListItem> => {
 console.log('response.json()');
 return response.json();
 })
 .then((item: IListItem): void => {
 console.log('Creation');
 this.usermessage(`List Item created successfully... '(Item Id: ${item.Id})`);
 }, (error: any): void => {
 this.usermessage('List Item Creation Error...');
 }); 
 }

 private usermessage(status: string): void {
 this.domElement.querySelector('.status').innerHTML = status;
 }
 private getListItemType(name: string) {
 let safeListType = "SP.Data." + name[0].toUpperCase() + name.substring(1) + "ListItem";
 safeListType = safeListType.replace(/_/g,"_x005f_");
 safeListType = safeListType.replace(/ /g,"_x0020_");
 return safeListType;
}
}

export interface IListItem {
 Title: string;
 Description: string;
 Id: number;
}

Now how to add the list Item we learned using REST and Typescript. to update and delete the list item very simple. just modify the context sphttpclient url

To update a list item, change the URL and pass item id to identify the item.

this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listname}')/items(${<span class="pl-smi">item</span>.<span class="pl-smi">Id</span>})`,

To delete a list item, change the URL and pass item id to identify the item.

 this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listname}')/items(${<span class="pl-smi">ItemId</span>})?$select=Id` 

To retrieve list Item, please refer my previous post 

To learn how to add property pane refer my previous post

The source code of the sample used in this article is available on GitHub at https://github.com/jenkinsns/spfxlistoperations

To deploy this code in your Office 365 Sharepoint library as CDN refer my previous post