0

I have this scenario all the time: a list of entities (say Customer) and a form to edit the selected entity. I bind the form fields to properties of the currently selected entity like this:

<some-element value="${this.selectedCustomer.name}"></some-element>

This works as long as I have a selectedCustomer which is not always the case. When I don't have one, the form is supposed to be blank. I figured that the ternary operator could be used like this:

<some-element value="${this.selectedCustomer ? this.selectedCustomer.name : ''}"></some-element>

But then the problem goes on with the name property which might be null (looks artifical with Customer entities but is very important for me with nullable properties!). I can fix that with the ternary operator again:

<some-element value="${this.selectedCustomer ? (this.selectedCustomer.name ? this.selectedCustomer.name : '') : ''}"></some-element>

And this had to be done for all form fields for all entities. I just want ask for any experience whether this is the best way to do it?

Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37
NicolasR
  • 2,222
  • 3
  • 23
  • 38
  • 1
    You can use a shorter version: ` ` or with TypeScript 3.7: ` ` – jacekbj Feb 23 '20 at 20:33
  • I see, because of the conditional evaluation order. Thanks, that indeed shortens it a bit. – NicolasR Feb 24 '20 at 13:14
  • 1
    You can also put this kind of verification in a method and call it, it won't shorten your code, but make it easier to order and read. You can then create a generic function to do this kind of check, declare it in a superclass of all your element class and use it everywhere. – Arfost Feb 24 '20 at 17:08

1 Answers1

2

Because lit-html expressions are just JavaScript, you have to do error handling as you would do in any other plain JavaScript. In this case you need to guard against undefined and there's nothing lit-html can do about that because it never sees the expression, just the resulting value.

As pointed out in the comments, JavaScript itself has addressed this now with the optional chaining and nullish coalescing operators:

You last example can now look like this:

html`<some-element value=${this.selectedCustomer?.name ?? ''}></some-element>`

This is supported in Chrome, Firefox, Edge, Babel, TypeScript and should be coming soon to Safari.

Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37