sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.05k stars 4.07k forks source link

`#each` key is a pitfall #9224

Open brunnerh opened 11 months ago

brunnerh commented 11 months ago

Describe the problem

Again and again people have issues with #each because they insert into/remove from/sort the source array without using a key.

Keys are explained both in the docs and the tutorial but maybe Svelte is just a bit too accessible because apparently people sometimes read neither. As a result they do not even know about keying.

Describe the proposed solution

I do not have a concrete solution to this but thought about some options:

Alternatives considered

(see above)

Importance

nice to have

stephane-vanraes commented 11 months ago

Wouldn't this be easily captured by a linting rule instead ? Also: could there be scenarios where a key is explicitly not desired, or should that maybe be covered with an 'empty' key ?

{#each list as item ()}

This also assumes all items in the list are unique, if this is a simple application that for example lists the first names of kids in the soccer ream you could easily have duplicate items:

const players = ["Stephane", "Simon", "Rich", "Simon", "Ben"]
brunnerh commented 11 months ago

Wouldn't this be easily captured by a linting rule instead ?

That way it would only help those that actually use a linter, not sure how common that is. I for one do not use one unless I have to.

Also: could there be scenarios where a key is explicitly not desired, or should that maybe be covered with an 'empty' key ?

{#each list as item ()}

This also assumes all items in the list are unique [...]

Not having a key should be equivalent to just using the index as far as I know, that way you also do not run into issues with duplicates. So the shortest current syntax when explicitly setting it would be something like:

{#each list as item, i (i)}

I guess there could be a special syntax for this, but to me having only () looks a bit like something is missing.

sacrosanctic commented 8 months ago

Wouldn't this be easily captured by a linting rule instead ?

a linting rule already exists

sacrosanctic commented 8 months ago

What is the current behaviour when a key is not specified?

brunnerh commented 8 months ago

Identity is based on index, so it's only safe to add to/remove from the end of the array.