proposal-signals / signal-utils

MIT License
69 stars 6 forks source link

How would iterating a reactive array work? #41

Open R2D221 opened 2 months ago

R2D221 commented 2 months ago

Currently I see that this package provides many reactive collections, but all examples show getting a single element from the collection.

My question is, how does iterating an array to show an HTML tag per element work?

Imagine an example like this:

import { SignalArray } from 'signal-utils/array';

let arr = new SignalArray([1, 2, 3]);

<template>
    <ol>
    {{arr.map(x =>
        <li>{{x}}</li>
    )}}
    </ol>
</template>

Now, let's say at some point we add a new item:

arr.push(4);

This, of course, means adding a new <li> at the end of the list. But how does the mechanism work? You've mentioned before that this would be framework-dependent, but what would a reference implementation be like? Would the list be rerendered? Would it only append the last element? If so, how? How would the signals propagate to add just the last element without rerendering the previous ones?

NullVoxPopuli commented 2 months ago

vue, svelte, ember, and angular optimize this situation via custom syntax in the template.

I think we can do in JavaScript via a reactive version of Array.prototype.map.

As when the length of an array changes, we don't want to re-render any item in the array that's already been rendered.

This would be great to add (already an issue mentioning this: https://github.com/proposal-signals/signal-utils/issues/15 )

A couple reference implementations

I'm away from my computer today, but i can port this over soon, if no one else does by the time i get to it 🎉