Skip to content

In svelte action, $effect cannot listen to changes in options. #15624

@Sincenir

Description

@Sincenir

Feature Request

I want to use the new syntax to implement 'focusTrap action', but I can only implement basic init and destory, not the 'update' function in the original 'action'

Reproduction

e.g.
+page.svelte

<script lang="ts">
	import { focusTrap } from './action.svelte';
	let state = $state.raw(true);

	setInterval(() => {
		state = !state;
	}, 1000);
</script>

<div use:focusTrap={state}></div>

action.svelte.ts

export function focusTrap(node: HTMLElement, enabled = true) {
	function init() {
		console.log('init');
	}

	function destroy() {
		console.log('destroy');
	}

	$effect(() => {
		console.log('effect enable', enabled);

		if (enabled) init();
		return destroy;
	});
}

Or can only create a new staate internally, then update the state via update.
action.svelte.ts

export function focusTrap(node: HTMLElement, enabled = true) {
        let curEnable = $state(enable)

	function init() {
		console.log('init');
	}

	function destroy() {
		console.log('destroy');
	}

	$effect(() => {
		console.log('effect enable', enabled);

		if (curEnable) init();
		return destroy;
	});

        return {update(enable) {curEnable = enable}}
}

Logs

-

System Info

svelte v5

Severity

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