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
$derivedwith stores via$storesyntax, but you can only use$storewithin components. You can usefromStoreas noted by @webJose outside of components (in.svelte.js/tsfiles), the object returned from that then can be used in$derived(or other reactive contexts).For extracting values I would use
$derivedin components or just a function when in an external module.$derivedcannot be exported directly, so you need some wrapper, having a$derivedin-between has little value.E.g.
Playground