Extracting Nested Properties from an External Svelte Store: Legacy Derived vs. $derived() Runes API #15202
-
I'm working with a Svelte store that comes from an external module (i.e. I don't control its creation). The store is defined like this: // store.js
import { writable } from 'svelte/store'
export const page = writable({
user: {
name: 'Kevin',
...
},
...
}) Since I only need the // In my Svelte component (Svelte 4)
<script>
import { page } from './store'
import { derived } from 'svelte/store'
// Derive the user object from the page store
const user = derived(page, ($page) => $page.user)
</script> Then in my template, I can use it like so: <p>Hello {$user.name}!</p> With Svelte 5's introduction of the new runes API (e.g.
Any insights, examples, or best practices on mixing these approaches or migrating to the new runes API (if applicable) would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Try |
Beta Was this translation helpful? Give feedback.
-
You can use For extracting values I would use E.g. const pageState = fromStore(page);
export function user() { return pageState.current.user; } |
Beta Was this translation helpful? Give feedback.
You can use
$derived
with stores via$store
syntax, but you can only use$store
within components. You can usefromStore
as noted by @webJose outside of components (in.svelte.js
/ts
files), the object returned from that then can be used in$derived
(or other reactive contexts).For extracting values I would use
$derived
in components or just a function when in an external module.$derived
cannot be exported directly, so you need some wrapper, having a$derived
in-between has little value.E.g.
Playground