SharePoint Online Lists: CRUD Operations with SPFx

Interacting with SharePoint lists is the most common SPFx task. Here’s how to do it properly with PnP JS.

Setup PnP JS

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

// In web part init
sp.setup({ spfxContext: this.context });

Read Items

const items = await sp.web.lists
  .getByTitle("Tasks")
  .items
  .select("Id", "Title", "Status")
  .filter("Status eq 'Active'")
  .top(100)
  .get();

Create Item

await sp.web.lists.getByTitle("Tasks").items.add({
  Title: "New Task",
  Status: "Active"
});

Update Item

await sp.web.lists.getByTitle("Tasks")
  .items.getById(1)
  .update({ Status: "Completed" });

Delete Item

await sp.web.lists.getByTitle("Tasks")
  .items.getById(1)
  .delete();

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.