kev2718
kev2718

Reputation: 47

Is there a way to set a Statement after an {#each} Block in Svelte?

im new to Svelte and build this component (https://reactjs.org/docs/thinking-in-react.html) to understand it a little better, after going through the tutorial. In Step 2 there is a section in the ProductTable class, where after an each loop theres the following statement lastCategory = product.category;. Is there a way one can write a statemente after this each block? Below is my Code so far.

<script>
    import ProductCategoryRow from './ProductCategoryRow.svelte';
    import ProductRow from './ProductRow.svelte';

    export let products;

    let lastCategory = null;
</script>


<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        {#each products as product}
            {#if product.category !== lastCategory}
                <ProductCategoryRow category={product.category} />
            {/if}
            <ProductRow product={product} />
            <!-- lastCategory = product.category (?) -->
        {/each}
    </tbody>
</table>

Sorry for my bad english and thanks in advance :)

Upvotes: 0

Views: 1971

Answers (2)

Thomas Hennes
Thomas Hennes

Reputation: 9949

As an alternative construct, you could also make use of an intermediary component and set up the logic there using <script context="module">.

Something like:

<script>
  import { onDestroy } from 'svelte'
  import ProductRowWrapper, { resetLastCategory } from './ProductRowWrapper.svelte'

  export let products

  // make sure the last category is reset to an empty string when
  // the entire product list is unmounted, in order to have a clean
  // initialization when it is mounted again with a different set of products
  onDestroy(resetLastCategory)
</script>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    {#each products as product}
      <ProductRowWrapper {product} />
    {/each}
  </tbody>
</table>
ProductRowWrapper.svelte

<script context="module">
  let lastCategory = ''

  export function resetLastCategory() {
    lastCategory = ''
  }
</script>

<script>
  import ProductCategoryRow from './ProductCategoryRow.svelte'
  import ProductRow from './ProductRow.svelte'

  export let product

  let displayCategory = product.category !== lastCategory

  lastCategory = product.category
</script>

{#if displayCategory}
  <ProductCategoryRow category={product.category} />
{/if}
<ProductRow {product} />

Upvotes: 0

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

You cannot do that in Svelte. Instead you would do a simple reverse lookup:

{#each products as product, i}
    {#if i !== 0 && product.category || products[i-1].lastCategory}
        <ProductCategoryRow category={product.category} />
    {/if}
        <ProductRow product={product} />
{/each}

(note that you could do this in React as well)

Upvotes: 1

Related Questions