Simple list operations in SPFx using PnPjs

In your SharePoint Framework solutions, you will likely want to interact with data stored in SharePoint. PnPjs offers a fluent api used to call the SharePoint rest services. This article outlines what options you have, how they work and what their advantages.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\Simple_List_Operations\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries

    sp.setup({
      spfxContext: this.props.spcontect
    });

Configure the custom properties

Create a new source code file under the src\webparts\simpleListOperations\components\ folder of the solution. Call the new file ISimpleListOperationsState.ts and use it to create a TypeScript Interface

export interface ISimpleListOperationsState {
  addText: string;
  updateText:IListItem[];
}

and one more in the same file

export interface IListItem {
  id: number;
  title: string;
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

public render(): void {
    const element: React.ReactElement<ISimpleListOperationsProps> = React.createElement(
      SimpleListOperations,
      {
        description: this.properties.description,
        spcontext: this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the SimpleListOperations.tsx file. First, add some import statements to import the types you defined earlier. Notice the import for ISimpleListOperationsPropsISimpleListOperationsState and IListItem. There are also some imports for the Office UI Fabric components used to render the UI of the React component and pnp sp imports.

import * as React from 'react';
import styles from './SimpleListOperations.module.scss';
import { ISimpleListOperationsProps } from './ISimpleListOperationsProps';
import { ISimpleListOperationsState, IListItem } from './ISimpleListOperationsState';
import { TextField, DefaultButton, PrimaryButton, Stack, IStackTokens, IIconProps } from 'office-ui-fabric-react/lib/';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

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

After the imports, define the icon for button component of Office UI Fabric

const stackTokens: IStackTokens = { childrenGap: 40 };
const DelIcon: IIconProps = { iconName: 'Delete' };
const ClearIcon: IIconProps = { iconName: 'Clear' };
const AddIcon: IIconProps = { iconName: 'Add' };

Replace this component with the following code.

 public render(): React.ReactElement<ISimpleListOperationsProps> {
    return (
      <div className={styles.simpleListOperations}>
        <div className={styles.container}>
          <div className={styles.row}>
            <div className={styles.column}>
              {this.state.updateText.map((row, index) => (
                <Stack horizontal tokens={stackTokens}>
                  <TextField label="Title" underlined value={row.title} onChanged={(textval) => { row.title = textval }} ></TextField>
                  <PrimaryButton text="Update" onClick={() => this._updateClicked(row)} />
                  <DefaultButton text="Delete" onClick={() => this._deleteClicked(row)} iconProps={DelIcon} />
                </Stack>
              ))}

              <br></br>
              <hr></hr>
              <label>Create new item</label>
              <Stack horizontal tokens={stackTokens}>
                <TextField label="Title" underlined value={this.state.addText} onChanged={(textval) => this.setState({ addText: textval })} ></TextField>
                <PrimaryButton text="Save" onClick={this._addClicked} iconProps={AddIcon} />
                <DefaultButton text="Clear" onClick={this._clearClicked} iconProps={ClearIcon} />
              </Stack>
            </div>
          </div>
        </div>
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

  constructor(prop: ISimpleListOperationsProps, state: ISimpleListOperationsState) {
    super(prop);
    this.state = {
      addText: '',
      updateText: [],
    };
    sp.setup({
      spfxContext: this.props.spcontext
    });
    if (Environment.type === EnvironmentType.SharePoint) {
      this._getListItems();
    }
    else if (Environment.type === EnvironmentType.Local) {
      // return (<div>Whoops! you are using local host...</div>);
    }
  }

place the below code after the react component code, these functions using PnPjs to get the data, create list items, update list item and delete the list item.

async _getListItems() {
    const allItems: any[] = await sp.web.lists.getByTitle("Colors").items.getAll();
    console.log(allItems);
    let items: IListItem[] = [];
    allItems.forEach(element => {
      items.push({ id: element.Id, title: element.Title });
    });
    this.setState({ updateText: items });
  }

  @autobind
  async _updateClicked(row: IListItem) {
    const updatedItem = await sp.web.lists.getByTitle("Colors").items.getById(row.id).update({
      Title: row.title,
    });

  }

  @autobind
  async _deleteClicked(row: IListItem) {
    const deletedItem = await sp.web.lists.getByTitle("Colors").items.getById(row.id).recycle();
    this._getListItems();
  }

  @autobind
  async _addClicked() {
    const iar: IItemAddResult = await sp.web.lists.getByTitle("Colors").items.add({
      Title: this.state.addText
    });
    this.setState({ addText: '' });
    this._getListItems();
  }

  @autobind
  private _clearClicked(): void {
    this.setState({ addText: '' })
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

5 thoughts on “Simple list operations in SPFx using PnPjs

  1. Mainak July 24, 2020 / 5:23 pm

    Awesome post.Utilized the concept in my project

    Liked by 1 person

  2. Chaitanya July 28, 2020 / 5:19 pm

    Ravi i am struggling with the grid design can help me with render method for four columns of the grid : Product name , description , Price , Price code

    with aligned grid ???

    Like

Comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s