In this blog, we are going to see how to get the list based on the url using PnP JavaScript component.

To know more about this JavaScript library, check the below links

JavaScript Example:

The below steps and code snippets used to get the SharePoint list based on url using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script> 
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>
  
<span id="listInfo"></span>

<script type="text/javascript">  
//web.getList('<RelativeURL>') returns the SharePoint list based on the relative url
$pnp.sp.web.getList("/sites/development/Lists/sample")
    .get().then(function(data) {
        console.log(data);
        document.getElementById("listInfo").innerHTML = "List is available.";
    }).catch(function(err) {
        console.log("Error: " + err);
        document.getElementById("folderInfo").innerHTML = "Error in getting List: " + err;
    });
</script>

  1. On Success, it returns the list information.
  2. On Failure , the code returns the below exception
    ProcessHttpClientResponseException: Error making HttpClient request in queryable: [404] Not Found

Typescript Example:

Typescript is the superset of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript. The below is the typescript example for getting the SharePoint List based on relative url.

import pnp from "sp-pnp-js";

pnp.sp.web.getList("/sites/development/Lists/sample").get().then(data => {
    this.domElement.querySelector("#listInfo").innerHTML = "List is available"
}).catch(err => {
    this.domElement.querySelector("#listInfo").innerHTML = "Error in getting List: "+ err
});
Get List based on url using PnP JavaScript Library
Tagged on:                     

3 thoughts on “Get List based on url using PnP JavaScript Library

Leave a Reply

Your email address will not be published. Required fields are marked *