spfx insert and update using sharepoint rest api
Insert into into sharepoint
To insert an item into a SharePoint list using SharePoint Framework (SPFx) without a framework, you can use the SharePoint REST API. Here's a simple example of how you can achieve this in an SPFx web part:
1. Open your SPFx project in your preferred code editor.
2. In your web part code, you can make use of the SharePoint REST API to add an item to a list. Below is an example using the
SPHttpClient:
typescriptimport { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { sp } from '@pnp/sp';
import { IMyWebPartProps } from './IMyWebPartProps';
export default class MyWebPart extends BaseClientSideWebPart<IMyWebPartProps> {
public render(): void {
// Your web part rendering code
}
protected async onInit(): Promise<void> {
// Ensure the SharePoint PnP JS is initialized
sp.setup({
spfxContext: this.context
});
// Add an item to the SharePoint list
await this.addListItem();
// Call the parent onInit method
return super.onInit();
}
private async addListItem(): Promise<void> {
// Specify the SharePoint list name and endpoint
const listName: string = 'YourListName';
const endpoint: string = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listName}')/items`;
// Define the item properties
const itemProperties: any = {
Title: 'New Item Title',
OtherColumn: 'Other Column Value',
// Add other columns as needed
};
// Use the SPHttpClient to make a POST request to add the item
const response = await this.context.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
},
body: JSON.stringify(itemProperties),
});
// Check if the item was successfully added
if (response.ok) {
console.log('Item added successfully');
} else {
console.error(`Error adding item: ${response.statusText}`);
}
}
}Make sure to replace 'YourListName' with the actual name of your SharePoint list and update the itemProperties object with the column values you want to set.
Remember to handle errors appropriately and customize the code according to your specific requirements.
2. Update item into sharepoint list
To update an item in a SharePoint list using SharePoint Framework (SPFx) without a framework, you can continue to use the SharePoint REST API. Here's an example of how to update an item in an SPFx web part:
Open your SPFx project in your preferred code editor.
In your web part code, make use of the SharePoint REST API to update an item. Below is an example using the
SPHttpClient:
typescriptimport { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { sp } from '@pnp/sp';
import { IMyWebPartProps } from './IMyWebPartProps';
export default class MyWebPart extends BaseClientSideWebPart<IMyWebPartProps> {
public render(): void {
// Your web part rendering code
}
protected async onInit(): Promise<void> {
// Ensure the SharePoint PnP JS is initialized
sp.setup({
spfxContext: this.context
});
// Update an item in the SharePoint list
await this.updateListItem();
// Call the parent onInit method
return super.onInit();
}
private async updateListItem(): Promise<void> {
// Specify the SharePoint list name, item ID, and endpoint
const listName: string = 'YourListName';
const itemId: number = 1; // Replace with the actual item ID
const endpoint: string = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})`;
// Define the item properties to update
const updatedItemProperties: any = {
Title: 'Updated Item Title',
OtherColumn: 'Updated Column Value',
// Add other columns as needed
};
// Use the SPHttpClient to make a PATCH request to update the item
const response = await this.context.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
'X-HTTP-Method': 'MERGE',
'IF-MATCH': '*',
},
body: JSON.stringify(updatedItemProperties),
});
// Check if the item was successfully updated
if (response.ok) {
console.log('Item updated successfully');
} else {
console.error(`Error updating item: ${response.statusText}`);
}
}
}Make sure to replace 'YourListName' with the actual name of your SharePoint list, update itemId with the correct item ID, and customize the updatedItemProperties object with the column values you want to update.
Handle errors appropriately and adapt the code to meet your specific requirements.
working code
In this article, I will be giving you the code to write CRUD operations using REST API in SharePoint Framework Web Part using No JavaScript Framework.
I have a SharePoint List names Registration Details which has 4 columns Full Name (internal name is Title), Address, Email ID (internal name EmailID) and Mobile.
Create a SPFx web part and choose No JavaScript Framework at the end. Below is the file structure of the web part.
Open RestApiDemoWebPart.ts file. Make the changes in this file as per below code:
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './RestApiDemoWebPart.module.scss';
import * as strings from 'RestApiDemoWebPartStrings';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
export interface IRestApiDemoWebPartProps {
description: string;
}
interface IRegistrationDetails {
Title: string;
Address: string;
Mobile: number;
EmailID: string;
}
export default class RestApiDemoWebPart extends BaseClientSideWebPart<IRestApiDemoWebPartProps> {
private Listname: string = "Registration Details";
private listItemId: number = 0;
public render(): void {
this.domElement.innerHTML = `
<div>
<table>
<tr>
<td>Full Name</td>
<td><input type="text" id="idFullName" name="fullName" placeholder="Full Name.."></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="idAddress" name="address" placeholder="Address.."></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" id="idPhoneNumber" name="mobile" placeholder="Mobile Number.."></td>
</tr>
<tr>
<td>Email ID</td>
<td><input type="text" id="idEmailId" name="emailid" placeholder="Email ID.."></td>
</tr>
</table>
<table>
<tr>
<td><button class="${styles.button} find-Button">Find</button></td>
<td><button class="${styles.button} create-Button">Create</button></td>
<td><button class="${styles.button} update-Button">Update</button></td>
<td><button class="${styles.button} delete-Button">Delete</button></td>
<td><button class="${styles.button} clear-Button">Clear</button></td>
</tr>
</table>
<div id="tblRegistrationDetails"></div>
</div>
`;
this.setButtonsEventHandlers();
this.getListData();
}
private setButtonsEventHandlers(): void {
const webPart: RestApiDemoWebPart = this;
this.domElement.querySelector('button.find-Button').addEventListener('click', () => { webPart.find(); });
this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.save(); });
this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.update(); });
this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.delete(); });
this.domElement.querySelector('button.clear-Button').addEventListener('click', () => { webPart.clear(); });
}
private find(): void {
let emailId = prompt("Enter the Email ID");
this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items?$select=*&$filter=EmailID eq '${emailId}'`, SPHttpClient.configurations.v1)
.then(response => {
return response.json()
.then((item: any): void => {
document.getElementById('idFullName')["value"] = item.value[0].Title;
document.getElementById('idAddress')["value"] = item.value[0].Address;
document.getElementById('idEmailId')["value"] = item.value[0].EmailID;
document.getElementById('idPhoneNumber')["value"] = item.value[0].Mobile;
this.listItemId = item.value[0].Id;
});
});
}
private getListData() {
let html: string = '<table border=1 width=100% style="border-collapse: collapse;">';
html += '
<th>Full Name</th>
<th>Address</th>
<th>Email ID</th>
<th>Phone Number</th>
';
this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items`, SPHttpClient.configurations.v1)
.then(response => {
return response.json()
.then((items: any): void => {
console.log('items.value: ', items.value);
let listItems: IRegistrationDetails[] = items.value;
console.log('list items: ', listItems);
listItems.forEach((item: IRegistrationDetails) => {
html += `
<tr>
<td>${item.Title}</td>
<td>${item.Address}</td>
<td>${item.EmailID}</td>
<td>${item.Mobile}</td>
</tr>
`;
});
html += '</table>
';
const listContainer: Element = this.domElement.querySelector('#tblRegistrationDetails');
listContainer.innerHTML = html;
});
});
}
private save(): void {
const body: string = JSON.stringify({
'Title': document.getElementById('idFullName')["value"],
'Address': document.getElementById('idAddress')["value"],
'EmailID': document.getElementById('idEmailId')["value"],
'Mobile': document.getElementById('idPhoneNumber')["value"],
});
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items`,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'X-HTTP-Method': 'POST'
},
body: body
}).then((response: SPHttpClientResponse): void => {
this.getListData();
this.clear();
alert('Item has been successfully Saved ');
}, (error: any): void => {
alert(`${error}`);
});
}
private update(): void {
const body: string = JSON.stringify({
'Title': document.getElementById('idFullName')["value"],
'Address': document.getElementById('idAddress')["value"],
'EmailID': document.getElementById('idEmailId')["value"],
'Mobile': document.getElementById('idPhoneNumber')["value"],
});
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items(${this.listItemId})`,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'IF-MATCH': '*',
'X-HTTP-Method': 'PATCH'
},
body: body
}).then((response: SPHttpClientResponse): void => {
this.getListData();
this.clear();
alert(`Item successfully updated`);
}, (error: any): void => {
alert(`${error}`);
});
}
private delete(): void {
if (!window.confirm('Are you sure you want to delete the latest item?')) {
return;
}
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items(${this.listItemId})`,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'IF-MATCH': '*',
'X-HTTP-Method': 'DELETE'
}
}).then((response: SPHttpClientResponse): void => {
alert(`Item successfully Deleted`);
this.getListData();
this.clear();
}, (error: any): void => {
alert(`${error}`);
});
}
private clear(): void {
document.getElementById('idFullName')["value"] = "";
document.getElementById('idAddress')["value"] = "";
document.getElementById('idEmailId')["value"] = "";
document.getElementById('idPhoneNumber')["value"] = "";
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}
Comments
Post a Comment