Skip to content

ResizeObserver calls getItemKey with stale index for removed node #1147

@rf-

Description

@rf-

Describe the bug

#1144 added this code to the ResizeObserver for measuring elements:

const index = this.indexFromElement(node)

if (!node.isConnected) {
  this.observer.unobserve(node)
  this.elementsCache.delete(this.options.getItemKey(index))
  return
}

I believe this is causing an issue where getItemKey can be called with an index that doesn't match the underlying data from the most recent render. In my app, this showed up as an error thrown from getItemKey, since it was indexing into an array of items to look up the key and got an out-of-bounds index.

Like the bug fixed in #1135, this is related to DOM nodes that have been detached from the page because their list items have been removed. this.indexFromElement(node) reads the data-index property from the node; since the node has been removed from the page already, this information is definitely out of date and the index may be larger than the current count.

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/vigorous-architecture-prdzxt

Steps to reproduce

Open the CodeSandbox page. Within 30 seconds or so, it should show an error overlay saying getItemKey called with stale index, which means an index < count assertion failed in getItemKey.

Expected behavior

getItemKey should only ever be called with indices that are consistent with the count provided during the last render.

How often does this bug happen?

Sometimes

Screenshots or Videos

No response

Platform

Safari 18.6 and Electron 41.0.2 on macOS 15.7

tanstack-virtual version

3.13.22

TypeScript version

No response

Additional context

No response

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions