Leveraging SPFx with @pnp/sp for list creation

Currently, I am attempting to create a custom list using @pnp/sp. In my process, it is necessary for me to verify if the list already exists. If it does not exist, then I will proceed to create the list and add its columns accordingly.

The issue lies in the fact that the code below only works sporadically. This inconsistency may be due to the asynchronous nature of sp.web.* methods, causing potential problems.

Therefore, what is the proper approach to 1) checking for a specific list, 2) creating the list if it is not found, and 3) adding fields to the list?

sp.web.lists.ensure("SliceBox").then( List => {    
    List.fields.getByTitle("Body").get().catch( f => {
        f.fields.addMultilineText("Body", 4, true, false, false, true);
    });

    List.fields.getByTitle("Link").get().catch( f => {
        f.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
    });

    List.fields.getByTitle("Visible").get().catch( f => {
        f.fields.addBoolean("Visible");
    });
})
.catch( err => {
    console.log("> Failure: ", err);
});

Even attempting a more explicit method (as shown below) still encounters issues:

sp.web.lists.ensure("SliceBox").then( List => {
    sp.web.lists.getByTitle("SliceBox").fields.getByTitle("Body").get().catch( f => {
        f.fields.addMultilineText("Body", 4, true, false, false, true);
    });        
    // ... shortened for brevity ...
})
.catch( err => {
    console.log("> Failure: ", err);
});

Answer №1

Here is a snippet of my test code that is functioning perfectly.

sp.web.lists.ensure("SliceBox").then( sliceBox => {                        
      sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
        sliceBox.list.fields.addBoolean("Visible");
        alert('fieldAdded');
      });

  })

Update:

Give this a shot:

sp.web.lists.ensure("SliceBox").then( sliceBox => {                        
      sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
        sliceBox.list.fields.addBoolean("Visible").then(f =>{
          sliceBox.list.fields.getByTitle("Link").get().catch( f => {
            sliceBox.list.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
            alert('done');
        });
        })

      });

  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show the JSON data items in a React Native application

In my React Native application, I am dealing with a JSON file containing various data sets. One of the challenges I am facing is extracting specific information from this JSON and displaying it correctly. [ { "001": [ { " ...

Is it possible to use Typescript to store and access static global variables based on a unique key

I want to store variables in a static global file, like this: declare const MYVAR = 'Some unchanging data'; Later on, I would like to be able to retrieve the information using just the key 'MYVAR', for example: globalFile.findValue ...

Issue with default selection persisting in Angular 9 when using ngModel

I'm encountering an issue where I am able to successfully autofill a text box based on the state from another component. However, when I attempt to add ngModel to the text box in order to capture the value upon form submission, the value is getting cl ...

Sortable layouts and tables in Ionic 3

I found a great example of an Ionic table that I'm using as reference: https://codepen.io/anon/pen/pjzKMZ <ion-content> <div class="row header"> <div class="col">Utility Company Name</div> <div c ...

When the value of a react state is used as the true value in a ternary operator in Types

Attempting to implement sorting on a table is resulting in the following error: (property) direction?: "asc" | "desc" No overload matches this call. Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction? ...

Is there a way to transmit a live audio recording in Ionic to Firebase?

I'm looking for a way to achieve live speech-to-text recognition using Google API service in an Ionic frontend. I've been searching for a library that can capture audio in real-time on Ionic and stream it directly to Google Cloud's storage b ...

Leveraging the power of RXJS and typescript for executing work conditionally between Server and Client Code

I am in need of a function that will assess various conditions to determine if an object is eligible for editing. These conditions may exist on both the server and client sides. Certain conditions should halt further validation and return a value. ...

How can I convert Typescript absolute paths to relative paths in Node.js?

Currently, I am converting TypeScript to ES5/CommonJS format. To specify a fixed root for import statements, I am utilizing TypeScript's tsconfig.json paths property. For instance, my path configuration might look like this: @example: './src/&ap ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

Mapped types in Typescript do not allow the addition of extra properties

If I have a type definition like this: A 'Person' must have either the name or fullname property defined. type Person = { [k in "name" | "fullname"]: string; }; If I want to add one more required property, such as age, my ...

How can I stop the SvelteKit production node server from filling up the logs with "Error: not found /path/here"?

After developing a website using sveltekit, I decided to build it for production as a nodejs server and deploy it on my linux server with Caddy as a reverse proxy. Unexpectedly, upon starting the server, I began receiving error messages in the log such as ...

What is the best way to determine the property type dynamically in TypeScript based on the value of another property?

I have been working with Polymorphic relationships and currently have the following TypeScript interface defined: interface SubjectA {} interface SubjectB {} interface SubjectC {} enum SubjectType { SubjectA = 'Subject A', SubjectB = 'S ...

retrieve the name or path of the route currently being accessed

Here is the navigation bar code snippet: <nav class="menu"> <a routerLink="textArea" class="menu-item">text-area</a> <a routerLink="dropdown" class="menu-item">dropdown</a& ...

What causes a merge conflict to occur within a React and Typescript project?

I stumbled upon this code snippet in our React/Typescript - JSX/TSX project with an unresolved Git merge conflict. Interestingly, the code successfully compiles and runs in the browser! Upon transpilation, I noticed that the top element is recognized as t ...

Tips for providing all props to a React component while still including necessary props specified in an interface

Am I overlooking something or is this a different issue altogether? import * as React from 'react'; interface Props { value: string; } const MyComponent = (props: Props) => { const { value, ...rest } = props; return ( & ...

Angular chat integration

In my application, I have a parent component called "chat" with two child components - "sidebar" (which displays the user list) and "conversation detail" (which shows the chat with each user). The functionality I am aiming for is that when a user is clicke ...

Creating a complete fullstack application in Angular 2 starting from the basics

Can anyone suggest tutorials, whether they are free or paid, for building an Angular 2 full stack from scratch? I've come across various packages and generators, but I want to learn how to create my own structure. ...

What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.l ...

Using dual index variables in Angular 4's ngFor loop for iterating through arrays

Is there a way to generate unique index numbers for items printed only on Saturdays? Specifically, I want the index to start from 0 once Saturday begins and continue incrementing. The rest of the options should have the same index numbers. Any suggestions ...

Filtering an array of objects in TypeScript based on the existence of a specific property

I'm attempting to filter objects based on whether or not they have a specific property. For example: objectArray = [{a: "", b: ""}, {a: ""}] objectArray.filter( obj => "b" in obj ).forEach(obj => console. ...