i have a Svelte Store with a nested object inside.
(I don't want to flatten the store, since in my real use-case the order of the elements (arrays appear too) is very important.)
export const rootStore = writable({
test : {
a : 0
}
})
Now i want to pass the test
property of this store to a child component, and I am questioning myself, what would be the best way to do this.
I did it like that:
Parent.svelte
<script>
import Child from "./Child.svelte"
import {rootStore} from "./store.js";
rootStore.subscribe((value) => console.log(value))
</script>
<Child attributes={$rootStore.test}/>
<p>
Value of test.a is {$rootStore.test.a}
</p>
Child.svelte
<script>
import {rootStore} from "./store.js";
export let attributes;
const triggerUpdate = () => {
$rootStore = $rootStore;
}
</script>
<input type="number" bind:value={attributes.a}/>
<button on:click={triggerUpdate}>
Explicitly trigger update
</button>
But this doesn't seem a good idea, since now i am working on a reference of item
in my child component, that does not trigger other subscribers when I edit a
.
The edit will only become visible when I explicitly update the rootStore
object as done in triggerUpdate()
.
Here is the full REPL: https://svelte.dev/repl/57bce526799843b19838913cd598f201?version=3.50.1
Is it necessary to always work on the $rootStore
in the child components?
Should I only pass some IDs as properties to the child component, that will not be changed anytime?
Any ideas are welcome.
You just have to bind
the property to make it hook into updates:
<Child bind:attributes={$rootStore.test}/>