svelte-intersection-observer
svelte-intersection-observer copied to clipboard
IntersectionObserver inside Svelte #each block causes infinite loop
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
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
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>