Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte 5 bind value is getting more complex

I migrate my progect to svelte 5 and start using the power of runes but the code is buggy because the bind is not working anymore and i had to add some extra line of code. Here and example before and after the migration. I personally think in svelte 4 was way much simpler. Do you think i can make it better?

Before:

export let data: PageData;

<Player bind:data={data.news} />
<Actions bind:data={data.news} />

After:

interface Props { 
  data: PageData;
}
let { data }: Props = $props();
let news: Data = $state(data.news);
page.subscribe(() => (news = data.news));

<Player bind:data={data.news} />
<Actions bind:data={data.news} />
like image 482
Marcello Kabora Avatar asked Jan 18 '26 08:01

Marcello Kabora


1 Answers

There was rune for linking state before but that was removed.
The intended way to synchronize state that also needs to be written to, is to use an effect.

It should be this:

let news = $state(data.news);
$effect.pre(() => { news = data.news; });

You generally should not manually subscribe to stores, the subscription is not cleaned up automatically; you have to clean it up manually.

If you want to use a store with runes in a component, use the $-syntax in an $effect or $derived. So if you want to use the page store, e.g.:

const id = $derived($page.params.id);
like image 102
H.B. Avatar answered Jan 21 '26 07:01

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!