I don't understand this section in the tutorial: https://svelte.dev/tutorial/keyed-each-blocks.
I can see the things
array is updated correctly so the right thing.color
is passed as expected. But by the first sentence "By default, when you modify the value of an each
block, it will add and remove items at the end of the block, and update any values that have changed.", it seems to be saying that Svelte anyway removes the last block when clicking the button, then the remaining 4 blocks will be faced with the sliced things
, which is
[{ id: 2, color: '#6a00a8' },
{ id: 3, color: '#b12a90' },
{ id: 4, color: '#e16462' },
{ id: 5, color: '#fca636' }]
And since initial
is declared as const
, it cannot be updated anymore, so the colors of thing.id
1--4 remains.
Is this a correct understanding? Is this default behavior assuming the each
blocks are exchangeable?
Then it says using thing.id
as the key for the each
blocks will solve the issue, namely, {#each things as thing (thing.id)}
. I don't understand how the keys are used in the each
blocks and what was the default key if thing.id
is not provided. And why the default key (if there is one, or the default no-key) doesn't work while providing thing.id
does.
Thanks for the clarification.