Skip to content

Svelte getKey is called with undefined when data length decreases #851

@Lechros

Description

@Lechros

Describe the bug
When the data array passed to <Virtualizer> length decreases, getKey can be invoked with undefined for some indices.

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

	in <unknown>
	in Virtualizer.svelte
	in +page.svelte
	in layout.svelte
	in root.svelte
	in undefined

    at getKey (+page.svelte:10:53)

To Reproduce
Minimal Svelte 5 example:

<script lang="ts">
  import { Virtualizer } from "virtua/svelte";

  let data = $state(Array.from({ length: 5 }, (_, i) => ({ id: i })));
</script>

<button type="button" onclick={() => data.pop()}>pop()</button>

<div>
  <Virtualizer {data} getKey={(item, index) => item.id}>
    {#snippet children(item, index)}
      {item}
    {/snippet}
  </Virtualizer>
</div>

Expected behavior
getKey should only be called with a valid data[index] for the current data.

Platform:

  • OS: Windows
  • Browser: Chrome
  • Version of this package: 0.48.5
  • Version of framework: svelte 5.51.2

Additional context
I think it was fine in virtua 0.41.5.

AI analysis:

  • The mismatch occurs in Virtualizer.svelte at the {#each indexes as index (getKey(data[index]!, index))} line: indexes comes from $derived(store.$getRange(...)), while the store’s length is updated only inside $effect.pre. So when the parent updates data to a shorter array in the same tick, the component runs with new data but old indexes, and the each block calls getKey(data[index], index) for indices that are out of bounds for the new data.
  • Same underlying issue can appear with React/Vue/Solid if the framework’s effect/update order causes data to update before the virtual store’s length is applied in the same frame.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions