Connecting to other sites with PnP JS 3.0.0

With the release of PnP JS 3.0.0, you’ll need to tweak a bit of code throughout your project. One particular case that has caused me issues in the migration is cases where you opened a Web or Site directly using it’s constructor such as the following:

const web = Web(myWebUrl);
const site = Site(mySiteUrl);

This syntax is no longer valid in PnP JS 3.0.0, however it won’t cause a build error. When your code executes a promise doesn’t get returned and your try / catch block won’t catch it. This leaves you trying to figure out why the rest of your code mysteriously stopped executing. I’ve already ran into this a couple of times in my migration effort.

This is not hard to fix with PnP JS 3.0.0 but the syntax is quite a bit different. First, get the imports you need:

import { SPFI, spfi, SPFx } from "@pnp/sp";
import { AssignFrom } from "@pnp/core";

To get a Site or Web object for another site, you’ll need to get a new SPFI object first. There are a few ways to do this but here is the one I went with. This assumes that you already established an SPFI object earlier for the current site and assigned it to this.sp.

const spSite = spfi(siteUrl).using(AssignFrom(this.sp.web));

Now that you have a new SPFI object tat has a Site object available to you such as:

await spSite.site.getContextInfo();
const webTitle = (await spSite.site.rootWeb()).Title;

That should get you going. Be sure and read the Getting Started guide for 3.0.0 to fully understand all of the changes when upgrading.

Published by coreyroth

Corey Roth is the Vice President of Engineering at UnlimitedViz where he helps build the tyGraph product line for data analytics in Microsoft 365. Corey is an eleven-time recipient of the Microsoft MVP award in Office Apps and Services. Corey helps ISVs develop mobile-first applications for Office 365 using technologies such as Ionic Framework and Azure. Corey has always focused on rapid adoption of new Microsoft technologies including Office 365 and Azure. In his spare time, Corey works with his wife, Jennifer, on their product BrewZap, a mobile app platform for breweries.

Leave a Reply

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 )

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

%d bloggers like this: