A Detailed Guide on Using PnPjs to Perform CRUD Operations on SharePoint List Items

In this article, we will walk through how to perform various operations—Create, Read, Update, and Delete (CRUD)—on SharePoint list items using PnPjs. PnPjs simplifies working with SharePoint data, making it easier to interact with the SharePoint REST API.

We’ll cover:

  1. Introduction to PnPjs
  2. Setting up PnPjs in a SharePoint Framework (SPFx) project
  3. Connecting to SharePoint using PnPjs (replacing const sp = spfi(...);)
  4. Performing CRUD operations on SharePoint list items
  5. Sample with all operations

1. Introduction to PnPjs

PnPjs is an open-source library designed to work with SharePoint Online and SharePoint On-Premises. It provides fluent and easy-to-use methods for interacting with SharePoint objects like lists, items, sites, and more.

Some advantages of using PnPjs include:

  • Simplicity: It abstracts much of the complexity involved in working with the SharePoint REST API.
  • TypeScript support: PnPjs is built with TypeScript, providing strong type checking.
  • Performance: It is optimized for performance, and supports batching requests to minimize API calls.

2. Setting up PnPjs in a SharePoint Framework (SPFx) Project

Before we can start using PnPjs, we need to set up the project. Follow these steps to install and configure PnPjs in your SPFx project.

  1. Create a new SPFx project (if you don’t have one):
   yo @microsoft/sharepoint
  1. Install PnPjs:
   npm install @pnp/sp @pnp/logging @pnp/common @pnp/odata
  1. Configure PnPjs:
    In your web part file (e.g., MyWebPart.ts), initialize PnPjs in the onInit() method. This method ensures that PnPjs knows how to connect to the current SharePoint site.
   import { spfi, SPFx } from "@pnp/sp";
   import "@pnp/sp/webs";
   import "@pnp/sp/lists";
   import "@pnp/sp/items";

   export default class MyWebPart extends BaseClientSideWebPart<IMyWebPartProps> {

     private sp;

     public onInit(): Promise<void> {
       return super.onInit().then(_ => {
         // Configure PnPjs to use the current SPFx context
         this.sp = spfi().using(SPFx(this.context));
       });
     }
   }
  • spfi() is the PnPjs factory function used to create an instance of PnPjs.
  • SPFx(this.context) binds the SPFx context to the PnPjs instance. Important: PnPjs needs to be initialized with the current SharePoint context so it can authenticate API calls properly.

3. Connecting to SharePoint Using PnPjs

The line const sp = spfi(...); is essential for initializing PnPjs in a way that allows it to interact with SharePoint lists and items. Here’s what it does:

  • spfi(): This function initializes a new PnPjs instance that can be configured to work with various extensions (like SPFx, Graph, etc.).
  • using(SPFx(this.context)): This method configures the PnPjs instance to use the SharePoint Framework context, which provides the necessary authentication and base URL for API calls. This is critical when working within the SPFx environment.

In a typical scenario:

const sp = spfi().using(SPFx(this.context));
  • sp: This is your main connection to SharePoint and provides all the methods to interact with SharePoint objects like lists, sites, etc.

Substitute Example:
If you’re outside an SPFx environment (e.g., in a standalone React app), you could replace the context binding with:

const sp = spfi("https://your-sharepoint-site-url");

Here, instead of using the SPFx context, you directly provide the SharePoint site URL.


4. Performing CRUD Operations with PnPjs

Let’s now cover how to perform Create, Read, Update, and Delete operations on SharePoint list items using PnPjs.

Create a List Item

To add a new item to a SharePoint list, you can use the add method.

import { IItemAddResult } from "@pnp/sp/items";

const addItem = async () => {
  const list = this.sp.web.lists.getByTitle("MyList");
  const item: IItemAddResult = await list.items.add({
    Title: "New Item",
    Description: "This is a description"
  });
  console.log(item);
};
  • getByTitle(“MyList”): Retrieves the list with the title “MyList”.
  • items.add(): Adds a new item with the specified fields (Title, Description).
Read List Items

To retrieve items from a SharePoint list, use the select and get() methods.

const getItems = async () => {
  const items = await this.sp.web.lists.getByTitle("MyList").items.select("Title", "Description").get();
  console.log(items);
};
  • items.select(): Specifies the fields to retrieve (Title, Description).
  • get(): Executes the query and retrieves the items.
Update a List Item

To update an item, use the update method along with the item’s ID.

const updateItem = async (itemId: number) => {
  const item = await this.sp.web.lists.getByTitle("MyList").items.getById(itemId).update({
    Title: "Updated Item Title"
  });
  console.log(item);
};
  • getById(itemId): Retrieves the item by its ID.
  • update(): Updates the specified fields (Title in this case).
Delete a List Item

To delete an item, use the delete method.

const deleteItem = async (itemId: number) => {
  await this.sp.web.lists.getByTitle("MyList").items.getById(itemId).delete();
  console.log(`Item with ID ${itemId} deleted`);
};
  • delete(): Deletes the item with the specified ID.

5. Full Sample: Performing All Operations

Below is a full example that demonstrates how to perform all CRUD operations within an SPFx web part.

import * as React from 'react';
import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import { IItemAddResult } from "@pnp/sp/items";

export default class MyWebPart extends BaseClientSideWebPart<{}> {

  private sp;

  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      this.sp = spfi().using(SPFx(this.context));
    });
  }

  // Add a new item
  private async addItem() {
    const item: IItemAddResult = await this.sp.web.lists.getByTitle("MyList").items.add({
      Title: "New Item",
      Description: "This is a new item"
    });
    console.log(item);
  }

  // Get all items
  private async getItems() {
    const items = await this.sp.web.lists.getByTitle("MyList").items.select("Title", "Description").get();
    console.log(items);
  }

  // Update an item
  private async updateItem(itemId: number) {
    const item = await this.sp.web.lists.getByTitle("MyList").items.getById(itemId).update({
      Title: "Updated Title"
    });
    console.log(item);
  }

  // Delete an item
  private async deleteItem(itemId: number) {
    await this.sp.web.lists.getByTitle("MyList").items.getById(itemId).delete();
    console.log(`Item with ID ${itemId} deleted`);
  }

  public render(): React.ReactElement<{}> {
    return (
      <div>
        <button onClick={() => this.addItem()}>Add Item</button>
        <button onClick={() => this.getItems()}>Get Items</button>
        <button onClick={() => this.updateItem(1)}>Update Item</button>
        <button onClick={() => this.deleteItem(1)}>Delete Item</button>
      </div>
    );
  }
}

6. Conclusion

In this article, we have explored how to perform CRUD operations on SharePoint lists using PnPjs within an SPFx project. PnPjs provides a fluent and powerful API that makes working with SharePoint data easier and more efficient. By following the examples above, you can now create, read, update, and delete items from your SharePoint lists with ease.

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment