svelte
svelte copied to clipboard
Svelte 5: Changing of the items in #each block breaks order of the element
Describe the bug
In an #each block we print some messages, whenever we add a new message to the array we generate a temporary id for the message that is substituted by the one generated from the server whenever it's validated (in the repl that is simulated by the setTimeout). Both the id and the temporary id are used to generate the key for the #each block.
{#each messages as msg, i (`${msg.id}_${msg.tmpId ?? ""}`)}
{#if i === 0}
<p>first</p>
{/if}
<p>{msg.content}</p>
{/each}
The new message is always added at the end, but when the key changes it is moved upwards while maintaining the same position in the array, this is happening only if the #if block is present. It works as expected in the next examples
{#each messages as msg, i (`${msg.id}_${msg.tmpId ?? ""}`)}
<p>{msg.content}</p>
{/each}
{#each messages as msg, i (`${msg.id}_${msg.tmpId ?? ""}`)}
<div>
{#if i === 0}
<p>first</p>
{/if}
<p>{msg.content}</p>
</div>
{/each}
This was working fine until next.158 and it was definitely broken in next.162 and also in the current version next.166
Reproduction
Logs
No response
System Info
Tested on the REPL with the last versions of chrome, firefox and safari on mac os and chrome on windows
Severity
blocking an upgrade