svelte-intersection-observer icon indicating copy to clipboard operation
svelte-intersection-observer copied to clipboard

IntersectionObserver inside Svelte #each block causes infinite loop

Open matthew-ia opened this issue 3 years ago • 3 comments

Not sure if this is an expected limitation or a bug, or perhaps specific to my project, but I get an infinite loop that locks up the app when I place <IntersectionObserver> into an #each block:

<script>
  import IntersectionObserver from 'svelte-intersection-observer';
  import Some from '$components/some.svelte';

  const sections = [
    {
      id: 'some',
      node: undefined,
      intersecting: undefined,
      component: Some,
    },
  ];
</script>

{#each sections as {id, node, intersecting, component}}
  <IntersectionObserver element={node} bind:intersecting>
    <section 
      id={id} 
      class:intersecting={intersecting} 
      bind:this={node}
    >
      <svelte:component this={component} />
    </section>
  </IntersectionObserver>
{/each}

Related: #63

matthew-ia avatar Apr 16 '23 04:04 matthew-ia

your code should work checkout this REPL example I made based on your code (just add threshold option, background & text color for better visualization while scrolling): https://svelte.dev/repl/60d4410aae7c48fb96b68b220e3495f8?version=3

lvnam96 avatar Apr 21 '23 21:04 lvnam96

I can't understand why the script is triggered only when the very last element id=3 is reached and puts the class "intersecting" on all 3 elements at once?

Where is my mistake?


<script lang="ts">
    import IntersectionObserver from "svelte-intersection-observer";

    let intersecting: boolean;
    let node: any;

    const data = [
        {
            id: 1,
            text: "aa",
        },
        {
            id: 2,
            text: "aa",
        },
        {
            id: 3,
            text: "aa",
        },
    ];
</script>

<style>
    .item {height: 50vh; }
</style>

<main>
    {#each data as item}
        <IntersectionObserver element={node} bind:intersecting threshold={0.7}>
            <section id="{item.id}" class:intersecting bind:this={node}>
                <div class="item">{item.text}</div>
            </section>
        </IntersectionObserver>
    {/each}
</main>

TrenchTown avatar Apr 20 '24 16:04 TrenchTown