Skip to content

Invalid code generated when a slot prop in an #each is a function that depends on the #each context. #5565

Closed
@dimfeld

Description

@dimfeld

Describe the bug

Code such as this:

<script>
    function setKey(key, value) { ... }
</script>

{#each keys as key}
    <slot {key} set={(value) => setKey(key, value)} />
{/each}

Generates this code:

const get_default_slot_context = ctx => ({ key: /*key*/ ctx[4], set: func });

function create_each_block(ctx) {
	let current;

	function func(...args) {
		return /*func*/ ctx[3](/*key*/ ctx[4], ...args);
	}

	const default_slot_template = /*#slots*/ ctx[2].default;
	const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[1], get_default_slot_context);

    // rest of the function here
}

func is defined inside create_each_block, not in get_default_slot_context, which causes a runtime error func is not defined.

This only happens if the value of set can't be hoisted outside the #each. If I don't use an #each loop or if I just remove the reliance on key like this set={(value) => setSomething(value)}, then everything works fine.

Looking back, 3.15 is the latest version of Svelte in which this worked.

To Reproduce

REPL: https://svelte.dev/repl/ad8e6f39cd20403dacd1be84d71e498d?version=3.29.3

Information about your Svelte project:

Svelte 3.29.3 in REPL.

Severity

Mildly inconvenient. I can work around it in this case by just using a static function for the slot prop and having the slot content just call the function with all the necessary arguments.

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