Skip to content

Undefined error in handler function when removing item={items[i]} from list #16860

@ed-tech-jim

Description

@ed-tech-jim

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions