Want Simplicity? Use the SharePoint PnP JavaScript Core Library

If you’re a SharePoint developer and not using the SharePoint PnP JavaScript Core Library… you’re working too hard.

In an earlier blog post, I looked at Typescript’s asynch/await feature as a way to simplify asynchronous SharePoint code. In retrospect, the SharePoint PnP JavaScript Core Library is a better, simpler, more elegant solution.

We’ve all been here…  deciding to drop what works… in favor of risking something better. For SharePoint client-side asynchronous code… this was an easy decision.  Here’s a short snippet to illustrate the point:

static GetRoles ()
{
let deferred = $.Deferred();
// Get the groups the current user belongs to.
//
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + 
"/_api/web/currentuser/Groups?$select=Title",
method: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (resultsData)
   {
   deferred.resolve(resultsData.d.results);
   },
error: function (jqXHR, textStatus, errorThrown)
   {
   window.console.log('error: loggedInUser.GetRoles returned an error');
   deferred.reject();
   }
});
return deferred.promise();
}

:
:

let promise1 = GetRoles();
:
$.when (promise1).done(function(data1)
   {
   processRoles (data1);

The GetRoles function make an asynch call into SharePoint, returning a promise, and the results are processed later. The GetRoles function is loaded with (typical) ugly asynch artifacts.

Now compare that version to this PnP version:
$pnp.sp.web.siteUsers.getById(_spPageContextInfo.userId).groups.select("Title").get()
.then ( groups=>
{
for (let group of groups)
   {
   // process groups...

Wow…  the GetRoles function is reduced to a one-liner…  with low-level asynch plumbing out of sight. I found that stringing multiple asynch calls together in parallel or serial fashion was easy, too.

I took the PnP code snippet above from a “traditional CSR” SharePoint list form…  where the PnP library was “included” via this JSLink expression:

https://cdnjs.cloudflare.com/ajax/libs/sp-pnp-js/3.0.2/pnp.min.js

I used the dollar sign, like this: “$pnp” to reference the PnP library in my (non-React) TypeScript code.

But in my React components, I import the PnP library like this:

import pnp from "sp-pnp-js";
 and reference the PnP library without the $,  like this:

pnp.sp.web.siteUsers.getById(loggedInUserId).get().then ( result=>
It’s all explained in the PnP Core Library github site.
I hope you find the SharePoint PnP JavaScript Core Library as enjoyable as I do.