Skip to content

svelte5: keyed each block not working as excepted (worked in svelte4) #10427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
FoHoOV opened this issue Feb 8, 2024 · 1 comment · Fixed by #10510
Closed

svelte5: keyed each block not working as excepted (worked in svelte4) #10427

FoHoOV opened this issue Feb 8, 2024 · 1 comment · Fixed by #10510
Assignees
Milestone

Comments

@FoHoOV
Copy link
Contributor

FoHoOV commented Feb 8, 2024

Describe the bug

Create an keyed each block then bind a component to an array like this:

{#each store.texts as text, i (text.id)}
	<div>
		<Paragraph bind:this={boundParagraphs[i]} text={text.text}></Paragraph>
		<button onclick={() => boundParagraphs[i].changeBackgroundToRed()}>
			change {text.text} backgroundColor
		</button>
		<button onclick={() => store.remove(store.texts[i].id)}>
			delete {text.text}
		</button>
	</div>
{/each}

If you remove an element from the store store.remove(...) then the onclick will call the wrong boundParagraph. See this repl

Reproduction

  1. go to this repl
  2. click on "delete b1"
  3. click on "change b2 backGroundColor"
  4. see nothing happen (expected behaviour is that b2 changes its color)
  • to see the normal behaviour before doing anything just press on "change X backgroundColor"
  • it works without using a keyed each block (by removing the (text.id) from each block)

Logs

Cannot read properties of null (reading 'changeBackgroundToRed')

System Info

System:
    OS: Windows 11 10.0.22621
    CPU: (16) x64 AMD Ryzen 7 4800H with Radeon Graphics
    Memory: 15.83 GB / 31.42 GB
  Binaries:
    Node: 20.4.0 - C:\Program Files\nodejs\node.EXE
    npm: 9.7.2 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (121.0.2277.106)
    Internet Explorer: 11.0.22621.1
  npmPackages:
    svelte: ^5.0.0-next.1 => 5.0.0-next.50

Severity

blocking an upgrade

@brunnerh
Copy link
Member

brunnerh commented Feb 8, 2024

Something about the index handling in bind:this seems off.
$inspect(boundParagraphs) shows that removal of the first element results in [null, Paragraph] rather than [Paragraph, null] which is the expected result from the second element shifting into the first position.

When removing from the end the progression is correct:
[Paragraph, Paragraph] => [Paragraph, null] => [null, null]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants