Now that we know how to find lists, we can change our code a bit. What we are doing next is checking if a list exists, and if it doesn't, we are going to create it.
Add the following function to your web part class.
private _createSharePointList(): void {
const getListUrl: string = this.context.pageContext.web.absoluteUrl
+ "/_api/web/lists/GetByTitle('My List')";
this.context.spHttpClient.get(getListUrl, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
if (response.status === 200) {
alert("List already exists.");
return; // list already exists
}
if (response.status === 404) {
const url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists";
const listDefinition : any = {
"Title": "My List",
"Description": "My description...