A Complete Guide to Getting and Setting Fields Value using PnP JS in SPFx

This article provides the complete Guide to Getting and Setting Fields value using PnP JS in SharePoint Framework (SPFx).

Install the library and required dependencies

npm install @pnp/sp --save

For PnP js selective import, refer PnP js site. I just imported below

import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/site-users/web";
import { ISiteUserProps } from "@pnp/sp/site-users/";
import "@pnp/sp/fields";

Get a list item

const list = sp.web.lists.getByTitle("GetSet");
const item: any = await list.items.getById(1).get();

Single line of text

//get value
let textvalue: string = item["Title"];
//set value 
const i = await list.items.getById(1).update({
  Title: textvalue
});

Multiple lines of text (Plain text)

//get value
let multipleLineTextValue: string = item["MultipleLinesText"];
//set value 
const i = await list.items.getById(1).update({
  MultipleLinesText: multipleLineTextValue
});

Multiple lines of text (Enhanced rich text)

//get value
let multipleLineHTMLValue: string = item["MultipleLinesHTML"];
//set value 
const i = await list.items.getById(1).update({
  MultipleLinesHTML: multipleLineHTMLValue
});

Choice (single selection)

//get value
let singleChoice: string = item["Location"];
//set value 
const i = await list.items.getById(1).update({
  Location: singleChoice
});

Choice (multiple selections)

//get value
let multiChoice: string[] = item["Locations"];
//set value 
const i = await list.items.getById(1).update({
  Locations: { results: multiChoice }
});

Number

//get value
let numvervalue: number = item["Quantity"];
//set value 
const i = await list.items.getById(1).update({
  Quantity: numvervalue
});

Currency

//get value
let currencyvalue: number = item["Cost"];
//set value 
const i = await list.items.getById(1).update({
  Cost: currencyvalue
});

Date and Time

//get value
let datevalue: Date = item["BirthDay"];
//set value 
const i = await list.items.getById(1).update({
  BirthDay: datevalue
});

Lookup (single selection)

PnP always only return id value, also we get the value from different field name, Example <Field Internal Name> + ‘Id’. So “Id” is always added in the suffix of your filed internal name

//get value
let lookupvalue: number = item["ColorId"];
//set value 
const i = await list.items.getById(1).update({
  ColorId: lookupvalue
});

Lookup (multiple selection)

//get value
let lookupvalues: number[] = item["ColorsId"];
//set value 
const i = await list.items.getById(1).update({
  ColorsId: { results: lookupvalues }
});

Yes/No

//get value
let yesnovalue: boolean = item["IsActive"];
//set value 
const i = await list.items.getById(1).update({
  IsActive: yesnovalue
});

Person or Group (single selection)

PnP always only return id value, also we get the value from different field name, Example <Field Internal Name> + ‘Id’. So “Id” is always added in the suffix of your filed internal name

//get value
let uservalue: number = item["OwnerId"];
const user: ISiteUserProps = await sp.web.getUserById(uservalue).get();
console.log(user.LoginName)
//set value 
const i = await list.items.getById(1).update({
  OwnerId: uservalue
});
//FYI...
//import { ISiteUserProps } from "@pnp/sp/site-users/";

Person or Group (multiple selection)

//get value
let usersvalue: number[] = item["OwnersId"];
//set value 
const i = await list.items.getById(1).update({
  OwnersId: { results: usersvalue }
});

Hyperlink

//get value
let linkvalue: object = item["Reference"];
const Description = linkvalue["Description"];
const Url = linkvalue["Url"];
//set value 
const i = await list.items.getById(1).update({
  Reference: {
    "__metadata": { type: "SP.FieldUrlValue" },
    Description: Description,
    Url: Url
  }
});

Picture

let linkvalue: object = item["Image"];
const Description = linkvalue["Description"];
const Url = linkvalue["Url"];
//set value 
let setvalue = JSON.stringify({
                "fileName": Description,
                "serverUrl": Url.replace(file.fileAbsoluteUrl.replace(/.*\/\/[^\/]*/, ''), ''),
                "serverRelativeUrl": Url.replace(/.*\/\/[^\/]*/, '')
            });
const i = await list.items.getById(1).update({
  Image: setvalue 
});

Managed Metadata (single selection)

//get value
let tagvalue: any = item["Tag"];
//set value 
const i = await list.items.getById(1).update({
  Tag: {
    "__metadata": { "type": "SP.Taxonomy.TaxonomyFieldValue" },
    "Label": tagvalue.Label,
    'TermGuid': tagvalue.TermGuid,
    'WssId': '-1'
  }
});

Managed Metadata (multiple selection)

//get value
let tagsvalue: any = item["Tags"];
let tagsString: string = '';
tagsvalue.forEach(function (v, i) {
  tagsString += `${v.Label}|${v.TermGuid};`;
})
//set value 
const i = await list.items.getById(1).validateUpdateListItem([{
  ErrorMessage: null,
  FieldName: "Tags",
  FieldValue: tagsString,
  HasException: false
}]);

Code can be view in the GitHub

Sharing is caring!

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

5 thoughts on “A Complete Guide to Getting and Setting Fields Value using PnP JS in SPFx

  1. Can you made this post for Create operation?

    In PnP SPFx Control React, the PeoplePicker provided selected people data like this:

    [{
    id: “i:0#.f | membership | person1@someurl.com
    imageInitials: “P1”
    mageUrl: “https://someurl.com/sites/MyName/_layouts/15/userphoto.aspx?
    accountname=person1%40someurl.com&size=M”
    oginName: “i:0#.f | membership | person1@someurl.com
    optionalText: “”
    secondaryText: “person1@someurl.com”
    tertiaryText: “”
    text: “Person 1”
    }]

    Is there any way to Create or Update an item without using Person/Group’s id?

    Liked by 1 person

Comments