1

Please do not provide PNP code examples

I am updating the fields of a folder using rest api (code below is an example). Now, the problem with this approach is that I have many fields, around 35+, and if one of them throws an error because the value is not provided, then makes it difficult to debug.

I have fields of different types:DateTime, booleans, number, strings, etc. If one of them is not set, ie: no value provided, then the rest api call fails. The error response makes it difficult to debug as it does not tell you where the problem lies and I can't make all my fields required in the form. So, I have two questions?

1- how to ensure that when fields have no value they are ignored, so no error is thrown, eg: 
if 'eventDate' has no value, ignored it so no error is thrown because it is undefined
'Title': `Item ${new Date()}`,
'eventDate': `${obj.EventDate}` //<------ eg: if EventDate prop is not provided, it will throw an error.

2- how to provide better error handling? In other words: how to display more detailed error that shows where the problem lies rather then throw a general error?

private createItem(): void {
        this.updateStatus('Creating item...');
        this.getListItemEntityTypeName()
          .then((listItemEntityTypeName: string): Promise<SPHttpClientResponse> => {
            const body: string = JSON.stringify({
              '__metadata': {
                'type': listItemEntityTypeName
              },
              'Title': `Item ${new Date()}`
[.... other fields ....]
    });
    return this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.properties.listName}')/items`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=verbose',
          'odata-version': ''
        },
        body: body
      });
  })
  .then((response: SPHttpClientResponse): Promise<IListItem> => {
    return response.json();
  })
  .then((item: IListItem): void => {
    this.updateStatus(`Item '${item.Title}' (ID: ${item.Id}) successfully created`);
  }, (error: any): void => {
    this.updateStatus('Error while creating the item: ' + error);
  });}
1

If the fields are required, then you'll have to provide them. However, I suspect that the fields aren't required but you're trying to set them with undefined or something similar. It's a little difficult to tell with the information provided.

I'm guessing the issue is with the way you are building the body object. Try only initializing it with the required values and then only set the fields you want to update (those with values). Any values you don't want to set will be left out. Something like this:

const bodyObject: any = {
  '__metadata': {
    'type': listItemEntityTypeName
  },
  'Title': `Item ${new Date()}`,
};

if(typeof field2Value !== "undefined") {
  bodyObject.field2 = field2Value;
}
if(typeof field3Value !== "undefined") {
  bodyObject.field3 = field3Value;
}

const body: string = JSON.stringify(bodyObject);

Also, what's wrong with PnP? 😃

2
  • yes, there are required fields. Those are handled by validation. The problem is with other fields. I thought of putting a if check there, but I thought probably there is a more elegent away. There is nothing wrong with PnP, but the people in charge of the project do not want it, cause they consider it as a dependency. – Burre Ifort Oct 4 '20 at 8:25
  • 1
    Hi @BurreIfort - I am one of the maintainers for PnPjs. I am not sure from reading the issue what you think we don't want or consider a dependency. But if you have feedback on ways you think we can improve the library we would certainly like to hear about it. You can always use the issues list to start a discussion. Also - even if you don't want to use PnPjs you can use our code as a reference. We have lots of methods for adding fields, perhaps some of that can help you here. – Patrick Rodgers Oct 5 '20 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.