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.
Open the command prompt. Create a directory for SPFx solution.
- md spfx-crud-no-framework
Step 2
Navigate to the above-created directory.
Navigate to the above-created directory.
- cd spfx-crud-no-framework
Step 3
Run Yeoman SharePoint Generator to create the solution.
Run Yeoman SharePoint Generator to create the solution.
- yo @microsoft/sharepoint
Step 4
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
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.
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).
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.
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).
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.
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.
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.
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.
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.
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.
- 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.
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.
Open mystrings.d.ts under \src\webparts\noFrameworkCrud\loc\ folder.
Step 2
Rename DescriptionFieldLabel to ListNameFieldLabel.
- declare interface INoFrameworkCrudWebPartStrings {
- PropertyPaneDescription: string;
- BasicGroupName: string;
- ListNameFieldLabel: string;
- }
- declare module 'NoFrameworkCrudWebPartStrings' {
- const strings: INoFrameworkCrudWebPartStrings;
- export = strings;
- }
Step 3
In en-us.js file under \src\webparts\noFrameworkCrud\loc\ folder set the display name for listName property.
In en-us.js file under \src\webparts\noFrameworkCrud\loc\ folder set the display name for listName property.
- define([], function() {
- return {
- "PropertyPaneDescription": "Description",
- "BasicGroupName": "Group Name",
- "ListNameFieldLabel": "List Name"
- }
- });
Step 4
Open main webpart file (NoFrameworkCrudWebPart.ts) under \src\webparts\noFrameworkCrud folder.
Step 5
Rename description property pane field to listName.
Open main webpart file (NoFrameworkCrudWebPart.ts) under \src\webparts\noFrameworkCrud folder.
Step 5
Rename description property pane field to listName.
- import { Version } from '@microsoft/sp-core-library';
- import {
- BaseClientSideWebPart,
- IPropertyPaneConfiguration,
- PropertyPaneTextField
- } from '@microsoft/sp-webpart-base';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
- import { IListItem } from './IListItem';
- import styles from './NoFrameworkCrudWebPart.module.scss';
- import * as strings from 'NoFrameworkCrudWebPartStrings';
- export interface INoFrameworkCrudWebPartProps {
- listName: string;
- }
- export default class NoFrameworkCrudWebPart extends BaseClientSideWebPart<INoFrameworkCrudWebPartProps> {
- private listItemEntityTypeName: string = undefined;
- public render(): void {
- this.domElement.innerHTML = `
- <div class="${ styles.noFrameworkCrud }">
- <div class="${ styles.container }">
- <div class="${ styles.row }">
- <div class="${ styles.column }">
- <span class="${ styles.title }">Welcome to SharePoint!</span>
- <p class="${ styles.subTitle }">Customize SharePoint experiences using Web Parts.</p>
- <p class="${ styles.description }">${escape(this.properties.listName)}</p>
- <a href="https://aka.ms/spfx" class="${ styles.button }">
- <span class="${ styles.label }">Learn more</span>
- </a>
- </div>
- </div>
- </div>
- </div>`;
- }
- protected get dataVersion(): Version {
- return Version.parse('1.0');
- }
- protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
- return {
- pages: [
- {
- header: {
- description: strings.PropertyPaneDescription
- },
- groups: [
- {
- groupName: strings.BasicGroupName,
- groupFields: [
- PropertyPaneTextField('listName', {
- label: strings.ListNameFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
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.
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.
Model for List Item
Let us add a class (IListItem.ts) representing the list item.
- export interface IListItem {
- Title?: string;
- Id: number;
- }
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.
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.
- export default class NoFrameworkCrudWebPart extends BaseClientSideWebPart<INoFrameworkCrudWebPartProps> {
- private listItemEntityTypeName: string = undefined;
- public render(): void {
- this.domElement.innerHTML = `
- <div class="${ styles.noFrameworkCrud }">
- <div class="${ styles.container }">
- <div class="${ styles.row }">
- <div class="${ styles.column }">
- <span class="${ styles.title }">CRUD operations</span>
- <p class="${ styles.subTitle }">No Framework</p>
- <p class="${ styles.description }">Name: ${escape(this.properties.listName)}</p>
- <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
- <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
- <button class="${styles.button} create-Button">
- <span class="${styles.label}">Create item</span>
- </button>
- <button class="${styles.button} read-Button">
- <span class="${styles.label}">Read item</span>
- </button>
- </div>
- </div>
- <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
- <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
- <button class="${styles.button} update-Button">
- <span class="${styles.label}">Update item</span>
- </button>
- <button class="${styles.button} delete-Button">
- <span class="${styles.label}">Delete item</span>
- </button>
- </div>
- </div>
- <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
- <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
- <div class="status"></div>
- <ul class="items"><ul>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>`;
- this.setButtonsEventHandlers();
- }
- private setButtonsEventHandlers(): void {
- const webPart: NoFrameworkCrudWebPart = this;
- this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.createItem(); });
- this.domElement.querySelector('button.read-Button').addEventListener('click', () => { webPart.readItem(); });
- this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); });
- this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.deleteItem(); });
- }
- private createItem(): void {
- }
- private readItem(): void {
- }
- private updateItem(): void {
- }
- private deleteItem(): void {
- }
- }
In the command prompt type “gulp serve” to see the buttons on the webpart.
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.
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.
- private getLatestItemId(): Promise<number> {
- return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
- this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items?$orderby=Id desc&$top=1&$select=id`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'odata-version': ''
- }
- })
- .then((response: SPHttpClientResponse): Promise<{ value: { Id: number }[] }> => {
- return response.json();
- }, (error: any): void => {
- reject(error);
- })
- .then((response: { value: { Id: number }[] }): void => {
- if (response.value.length === 0) {
- resolve(-1);
- }
- else {
- resolve(response.value[0].Id);
- }
- });
- });
- }
Implement Create Operation
First, start by implementing the Create method, which will add an item to SharePoint list.
- private createItem(): void {
- const body: string = JSON.stringify({
- 'Title': `Item ${new Date()}`
- });
- this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'Content-type': 'application/json;odata=nometadata',
- 'odata-version': ''
- },
- body: body
- })
- .then((response: SPHttpClientResponse): Promise<IListItem> => {
- return response.json();
- })
- .then((item: IListItem): void => {
- this.updateStatus(`Item '${item.Title}' (ID: ${item.Id}) successfully created`);
- }, (error: any): void => {
- this.updateStatus('Error while creating the item: ' + error);
- });
- }
- private updateStatus(status: string, items: IListItem[] = []): void {
- this.domElement.querySelector('.status').innerHTML = status;
- this.updateItemsHtml(items);
- }
- private updateItemsHtml(items: IListItem[]): void {
- this.domElement.querySelector('.items').innerHTML = items.map(item => `<li>${item.Title} (${item.Id})</li>`).join("");
- }
We will use the REST API to read the latest item.
- private readItem(): void {
- this.getLatestItemId()
- .then((itemId: number): Promise<SPHttpClientResponse> => {
- if (itemId === -1) {
- throw new Error('No items found in the list');
- }
- this.updateStatus(`Loading information about item ID: ${itemId}...`);
- return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${itemId})?$select=Title,Id`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'odata-version': ''
- }
- });
- })
- .then((response: SPHttpClientResponse): Promise<IListItem> => {
- return response.json();
- })
- .then((item: IListItem): void => {
- this.updateStatus(`Item ID: ${item.Id}, Title: ${item.Title}`);
- }, (error: any): void => {
- this.updateStatus('Loading latest item failed with error: ' + error);
- });
- }
Firstly, we will get the latest item and update it.
- private updateItem(): void {
- let latestItemId: number = undefined;
- this.updateStatus('Loading latest item...');
- this.getLatestItemId()
- .then((itemId: number): Promise<SPHttpClientResponse> => {
- if (itemId === -1) {
- throw new Error('No items found in the list');
- }
- latestItemId = itemId;
- this.updateStatus(`Loading information about item ID: ${itemId}...`);
- return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${latestItemId})?$select=Title,Id`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'odata-version': ''
- }
- });
- })
- .then((response: SPHttpClientResponse): Promise<IListItem> => {
- return response.json();
- })
- .then((item: IListItem): void => {
- this.updateStatus(`Item ID1: ${item.Id}, Title: ${item.Title}`);
- const body: string = JSON.stringify({
- 'Title': `Updated Item ${new Date()}`
- });
- this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${item.Id})`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'Content-type': 'application/json;odata=nometadata',
- 'odata-version': '',
- 'IF-MATCH': '*',
- 'X-HTTP-Method': 'MERGE'
- },
- body: body
- })
- .then((response: SPHttpClientResponse): void => {
- this.updateStatus(`Item with ID: ${latestItemId} successfully updated`);
- }, (error: any): void => {
- this.updateStatus(`Error updating item: ${error}`);
- });
- });
- }
REST APIs are used to find and delete the latest item.
- private deleteItem(): void {
- if (!window.confirm('Are you sure you want to delete the latest item?')) {
- return;
- }
- this.updateStatus('Loading latest items...');
- let latestItemId: number = undefined;
- let etag: string = undefined;
- this.getLatestItemId()
- .then((itemId: number): Promise<SPHttpClientResponse> => {
- if (itemId === -1) {
- throw new Error('No items found in the list');
- }
- latestItemId = itemId;
- this.updateStatus(`Loading information about item ID: ${latestItemId}...`);
- return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${latestItemId})?$select=Id`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'odata-version': ''
- }
- });
- })
- .then((response: SPHttpClientResponse): Promise<IListItem> => {
- etag = response.headers.get('ETag');
- return response.json();
- })
- .then((item: IListItem): Promise<SPHttpClientResponse> => {
- this.updateStatus(`Deleting item with ID: ${latestItemId}...`);
- return this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items(${item.Id})`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- 'Accept': 'application/json;odata=nometadata',
- 'Content-type': 'application/json;odata=verbose',
- 'odata-version': '',
- 'IF-MATCH': etag,
'X-HTTP-Method': 'DELETE' - }
- });
- })
- .then((response: SPHttpClientResponse): void => {
- this.updateStatus(`Item with ID: ${latestItemId} successfully deleted`);
- }, (error: any): void => {
- this.updateStatus(`Error deleting item: ${error}`);
- });
- }
Step 1
On the command prompt, type “gulp serve”.
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.
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.
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

Read Operation
Update Operation
Delete Operation
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.
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.

Noman ShaikhPosted Sep 3, 2020, 2:49 PM
Thanks for the article. Would request you to please provide an article for CRUD operations on task list. I want to use bootstrap, jquery and jquery data table. People picker is an important control, would appreciate if you could help us in this regard.
Vineet DubeyPosted Mar 30, 2020, 12:58 AM
There is problem while inserting the Item In LIST... Do I need to create a List Employee in SharePoint Site or it will create automatically.? Even after creating list and passing URL explicitly also its not working.. this.props.spHttpClient.post(`https://learnspin91.sharepoint.com/_api/web/lists/getbytitle('${this.props.listName}')/items`, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=nometadata', 'Content-type': 'application/json;odata=nometadata', 'odata-version': '' },
satendra prasadPosted Feb 17, 2020, 11:22 PM
Hey, How do i connect this code with sharepoint as only adding a web part is not working and i am getting error in shttpclientresponse with a red line in visual code
satendra prasadPosted Feb 17, 2020, 9:58 PM
HI ,SPHttpClient getting a red line below this code and the buttons are not working too.
dilip kumarPosted Jan 21, 2020, 9:20 AM
Thanks for the article, i'm getting this error while creating the item " while creating the item: TypeError: Failed to fetch" please suggest.
mohammed kamelPosted Nov 23, 2019, 11:51 AM
Thanks for the article , i have problem when i click any button create,read,update,delete the message appear correctly but it refresh all the page immediately i don't know what is the reason for refreshing
Alistair HalpernPosted Sep 16, 2019, 10:41 AM
Thanks for the article. Suppose I want to be able to insert values based on what the user types into input boxes. How would I amend the createItem code?
karthik nibinPosted May 30, 2019, 2:27 PM
Nice Article ! Simple to follow !
Deepak hadpadPosted Apr 21, 2019, 3:45 AM
Hi , i am new to Spfx.... I have list name called Approval with two columns Title and Id . in code where to mention list name ? how Spfx typescript knows in which list to insert and update or other operation.Please help me with this
Amay KulkarniPosted Apr 10, 2019, 11:57 AM
Getting this issue : "cannot find module 'flatmap-stream' while gulp serve
maha lakshmiPosted Aug 9, 2018, 7:12 PM
Good article
Guest UserPosted Aug 9, 2018, 7:10 PM
Nice article