SPFx - PnP-JS-Core - Check if list exist in current web
-
29-12-2020 - |
Question
I want to check if list(by Display Name) exist in current web.
In pnp developer guide is no information on how to work with lists?
I need this for validate web property and i want to use pnp-core-library to do this:
private asyncTextBoxValidationMethod(value: string): Promise<string> {
if (value !== undefined && value.length > 3) {
var url = this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`;
return this.fetchLists(url).then((response) => {
var lists: ISPList[] = response.value;
var foundList: boolean = false;
lists.forEach((list: ISPList) => {
if (value === list.Title) {
foundList = true;
}
});
if (!foundList) {
// resolve promise with error message to display..
return Promise.resolve("Value entered did not match a list in this site!");
}
// otherwise resolve promise with an empty string..
return Promise.resolve("");
});
}
}
How to do this?
Solution
You can use the lists.ensure
method to check if the list exists or not.
Add the below import statement:
import pnp, { List, ListEnsureResult } from "sp-pnp-js";
In your method, you can use it as below:
// Use lists.ensure to always have the list available
pnp.sp.web.lists.ensure("Custom List").then((ler: ListEnsureResult) => {
if (ler.created) {
console.log("list exists");
//do some awesome stuff with the list
}
else{
console.log("list doesnt exists");
}
}
Reference - PnP Core debugging
OTHER TIPS
I have tested the PnP List existence check against SP Online. You may try the same with SPFx without SP.SOD
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/sp-pnp-js/2.0.7/pnp.js">
</script>
<script language="javascript" type="text/javascript">
$( document ).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
$pnp.sp.web.lists.filter("Title eq Employee34'").get().then(function(result)
{
if (result.length > 0) {
alert("List Exists");
} else {
alert("List Does Not Exist");
}
});
});
});
</script>
On Testing :
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange