Skip to content

Gotcha with ReactiveSet/Map iterators #830

@ollpu

Description

@ollpu

Describe the bug

Using .keys(), .values() or .items() on a ReactiveSet or ReactiveMap is meant to track all keys/values for changes. However, if the iterators are not consumed, then no tracking is registered.

This comes up when trying to declare dependencies of an asynchronous effect beforehand.

createEffect(() => {
  // Track set for changes
  void set.values();

  setTimeout(() => /* Use set contents... */);
});

Though the intention was to track the full content of the set, the above effect is not actually triggered by changes to the set.


The reason this happens is that the methods are implemented as generators like so:

*values(): MapIterator<V> {
this.#valueTriggers.track($OBJECT);
for (const value of super.values()) {
yield value;
}
}

The beginning of the method is not run until .next() is called for the first time.

I think the methods should not be generators themselves, rather just return super.values(). That would probably be more performant as well. SvelteSet & Map are implemented like this.

Happy to to write a PR if there is agreement.

Minimal Reproduction Link

https://stackblitz.com/edit/github-r2lfqdu4?file=src%2FApp.tsx

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