Below is an article explaining how to perform CRUD operations on SharePoint lists using PnPjs, maintaining all logic in a single TypeScript file. This version avoids React/JSX and focuses purely on TypeScript.
Performing CRUD Operations on SharePoint Lists using PnPjs with TypeScript
Managing SharePoint lists is a common task in modern SharePoint development. To perform efficient Create, Read, Update, and Delete (CRUD) operations, PnPjs is a powerful library that simplifies interaction with SharePoint. In this tutorial, I will guide you through how to perform these operations in TypeScript, using only one .ts file without React components.
Step 1: Setting up the PnPjs Library
Before proceeding with the code, ensure that PnPjs is installed in your SPFx (SharePoint Framework) project. You can install it by running:
npm install @pnp/sp @pnp/logging @pnp/common @pnp/odata --save
You also need to ensure that you are using TypeScript version 4.x or higher. Check your tsconfig.json and make sure the typescript dependency in your project is compatible.
Step 2: Initializing PnPjs in the Web Part
In your Web Part file, you will initialize PnPjs using the SPFx context. Here is how you set up PnPjs in the MyCrudWebPart.ts:
import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
export default class MyCrudWebPart extends BaseClientSideWebPart<{}> {
private sp: ReturnType<typeof spfi>;
public onInit(): Promise<void> {
return super.onInit().then(() => {
// Initialize PnPjs with the SPFx context
this.sp = spfi().using(SPFx(this.context));
});
}
public render(): void {
// Call a function to perform CRUD operations
this.performCrudOperations();
}
private async performCrudOperations() {
try {
// Create operation
await this.createItem();
// Read operation
const items = await this.readItems();
console.log("Retrieved items:", items);
// Update operation
await this.updateItem(items[0].Id);
// Delete operation
await this.deleteItem(items[0].Id);
} catch (error) {
console.error("Error performing CRUD operations:", error);
}
}
// Method to create a new list item
private async createItem() {
const list = this.sp.web.lists.getByTitle("MyList"); // Replace with your list title
await list.items.add({
Title: "New Item"
});
console.log("Item created successfully");
}
// Method to read items from the list
private async readItems() {
const list = this.sp.web.lists.getByTitle("MyList");
const items = await list.items();
return items;
}
// Method to update an existing list item
private async updateItem(itemId: number) {
const list = this.sp.web.lists.getByTitle("MyList");
await list.items.getById(itemId).update({
Title: "Updated Title"
});
console.log("Item updated successfully");
}
// Method to delete an item from the list
private async deleteItem(itemId: number) {
const list = this.sp.web.lists.getByTitle("MyList");
await list.items.getById(itemId).delete();
console.log("Item deleted successfully");
}
}
Explanation of the Code
- Initialization with SPFx Context: We initialize PnPjs using the
SPFxcontext (spfi().using(SPFx(this.context))). This allows us to communicate with the SharePoint API. - CRUD Operations:
- Create: The
createItemmethod adds a new item to the SharePoint list with aTitlefield. - Read: The
readItemsmethod retrieves all items from the list. - Update: The
updateItemmethod updates the title of a specified item. - Delete: The
deleteItemmethod removes an item from the list using itsId.
- Error Handling: The operations are wrapped in a
try-catchblock to handle any potential errors gracefully. - No JSX or React Components: Everything is contained in a single
.tsfile without using any JSX or React.
Step 3: Explanation of the Removed IItemAddResult
In previous versions of PnPjs, a common interface used for adding list items was IItemAddResult. However, starting with PnPjs version 3.x, this interface was removed. Now, when you add a new item, PnPjs directly returns the added item or throws an error.
Here’s an updated version of how the code works after the removal of IItemAddResult:
Before (Using IItemAddResult):
import { IItemAddResult } from "@pnp/sp/items";
const result: IItemAddResult = await list.items.add({
Title: "New Item"
});
console.log(result.data); // This is now outdated
After (Without IItemAddResult):
const item = await list.items.add({
Title: "New Item"
});
console.log(item); // Now returns the added item directly
As you can see, the change simplifies the API, and you no longer need to rely on IItemAddResult. Instead, the add() method returns the added item directly.
Step 4: Testing the Web Part
After adding this code to your Web Part, build and deploy the solution:
gulp build
gulp bundle --ship
gulp package-solution --ship
Upload the package to your App Catalog, and you should be able to see the results of the CRUD operations in the browser console (F12 Developer Tools).
Conclusion
This article explained how to perform CRUD operations on SharePoint lists using PnPjs with a purely TypeScript-based approach. We avoided using JSX or React, keeping all the logic in one .ts file, which makes it easy to integrate in projects where React is not used or desired.
By following the steps outlined, you should now be able to add, read, update, and delete SharePoint list items seamlessly. If you encounter any issues, check your PnPjs version and TypeScript configuration to ensure compatibility

Leave a comment