-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Open
Description
Describe the bug
To be honest not sure if this is a bug or not. If a list item component has a prop passed by e.g. item={items[i]}, then calls a prop function in a handler that results in it getting removed from the list (e.g. click triggers handleRemove() which calls the prop onRemove()), but then references its prop item in the same handler, it will cause an undefined error.
<!-- List.svelte -->
{#each items as item, i (item.id)}
<ListItem item={items[i]} onRemove={() => removeItem(item.id)} />
{/each}
<!-- ListItem.svelte -->
<script>
let { item, onRemove } = $props();
function handleRemove() {
onRemove();
// This will error because item is undefined if it was the last item in the list,
// otherwise it will log the label from the next item in the list
console.log(item.label + ' removed');
}
</script>
<li>
{item.label}
<button onclick={handleRemove}>
Remove
</button>
</li>
It doesn't happen if you pass in item={item} rather than item={items[i]}, but then you can't bind the prop.
Reproduction
https://svelte.dev/playground/d643912ca8d64a4ab4162a22086c715c?version=5.38.1
Logs
System Info
Playground, all 5.x.x versions
Severity
annoyance
Metadata
Metadata
Assignees
Labels
No labels