Param used as state not updated on navigation #15834
|
I am having a problem and wondered what is the most idiomatic way to implement this. Basically I have a path in a let itemSlug = $state( data.slug || null );The idea here being that I want to copy the value when landing on the page, but be able to change it later. I do this often with form inputs linked to query parameters. It usually works well, provided I wrap my page with a Anyway, my Oddly enough, when replacing the For simplicity sake, I could leave it since it is working. But it sounds incorrect to be able to change a derived value manually and fear it might not work in a later version of sveltekit. Also I am aware of Anyway I'd like to have the opinion of somebody who's more savvy than me and let me know what is the most idiomatic way to implement what I want. |
Replies: 1 comment 1 reply
|
What you're observing is correct behavior, and Why
Why let itemSlug = $derived(data.slug ?? null);
The "manual assignment to $derived" question You can assign to a This is valid and intentional in Svelte 5. The RFC for runes explicitly supports this pattern. It won't be removed — it's designed to enable the "local override with sync-back" pattern you're using. Most idiomatic approach for your case: // Source of truth from navigation
let itemSlug = $derived(data.slug ?? null);
// Local modifications (e.g., after button clicks with goto/replaceState)
// Just reassign itemSlug directly — it's the override mechanismIf you need the {#key itemSlug}
<YourContent slug={itemSlug} />
{/key}This remounts the inner component when |
What you're observing is correct behavior, and
$derivedis actually the right tool here. Let me explain why.Why
$statedoesn't reset on navigation$stateis initialized once when the component mounts. When you navigate to the same page (e.g., removing the slug from the URL), SvelteKit re-runsload()and updates thedataprop — but it does not unmount and remount the component. Your$statekeeps its last value because it was only initialized once, and navigation doesn't re-trigger initialization.Why
$derivedworks and is the correct pattern$derivedre-computes whenever its dependencies change — including whendatais updated by a newload()ca…