Read and Update SPFx WebPart Properties from code

How many times you need to save some data in SPFx WebPart properties but don’t want this property appear in Properties Panel ?

How we you can do it ? I will explain how to read and save WebPart Properties from code using the REST API /_api/sitepages/pages

I start to define all WebPart Properties as usual, in manifest WebPart file

In this sample I have 3 properties , Title, lists and pivotData, the pivotData is a property that I want read and save in code, and don’t be available in Properties Panel of WebPart.


Property Panel Configuration



How to Read a Property

Where are WebPart properties saved? The WebPart properties are saved in the page column named “CanvasContent1”, this column is an array that has an entry for each WebPart on the page.

Each array entry is a JSON string that has all the information about WebPart, the WebPart properties are in the object called “webpartdata” in the “properties” object.

CanvasContent1” has all the information about all WebParts that exist on the page, each entry has an “id” field this “Id” identifies the WebPart instance installed on the page, because we can have multiple WebPart instances on the page and when you gets information from “CanvasContent1“, we have to read the correct information for the WebPart.

To get information from the page you have to do an http get to /_api/sitepages/pages({i}), example of “CanvasContent1” returned.

CanvasContent1

Here the sample of read properties for List PivotTable WebPart (List PivotTable WebPart Post)



How to Save Property

To save a property, you need to update the “CanvasContent1” column with new values ​​for the properties object.

To save new values you have to do a http post to /_api/sitepages/pages/page({i})/checkout , I can’t save page if it is not checkout before and then /_api/sitepages/pages/page({i})/savepage with new values for “CanvasContent1” Column.

Here the sample for update “CanvasContent1” with new values for List PivotTable WebPart. (List PivotTable WebPart Post)

Happy SharePointing!

Sharing is Caring!