Search code examples
sappersvelte-3

Svelte {# if } block length is not possible. How to get the length of the if block


I have a page with products/items. Some with options that the user needs to choose and some with no options at all.

In my shopping cart page, I display this ordered items/products with the options user chose if needed. This is how I iterate over products/item and the options

{#each eachitem as item }
<li>
  Here it is : {item.item.id} -- {item.price} -- {item.qty}  
  {#if item.item.checkedoptions.checkoptions === 0  }
   <p> Display NO OPTIONS</p>
  {:else}
  
  {#each item.item.checkedoptions.checkoptions[1] as opti}
  <li style="list-style-type : none">
    Options : {opti.optionname} - {opti.optionvalue}
  </li>
  {/each}
  {/if}
</li>

{/each}

The issue is when there are no options, I get the error in my dev tools that reads "Cannot read property 'length' of undefined", of course because item.item.checkedoptions.checkoptions[1] is empty. I tried to use length but couldn't figure out how to attach it to item.item.checkedoptions.checkoptions do I put it inside () or [] or what? How do you write if statement that if item.... length === 0 {do something}?

If I can't get the length, how do I solve this problem, do I do something in the script before I iterate?

How do you solve this issue?


Solution

  • In your if statement you are not actually checking the length of checkoptions you are comparing it directly with 0

    You should change this to #if item.item.checkedoptons.checkoptions.length === 0