Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte dynamic component assignment updates

In Svelte, I am using the value of a store to change the active component on a page, which is working as I would expect.

<script lang="ts">
    import { eventData } from "./store";
    import A from "./components/A.svelte";
    import B from "./components/B.svelte";

    let element = A;

    eventData.subscribe(({ showB }) => {
        if (showB) {
            element = B;
        } else {
            element = A;
        }
    });
</script>

<div>
    <svelte:component this={element} />
</div>

My question is if doing this creates one instance each of A and B which gets swapped in and out as needed, or if it creates a new instance on every change. For example, if I make an HTTP request to load some data in element B, does it run that every time I switch or does it run it once and keep the instance of B stored?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The svelte documetation says

The svelte:component element renders a component dynamically, using the component constructor specified as the this property. When the property changes, the component is destroyed and recreated.

https://svelte.dev/docs/special-elements#svelte-component

So you will get new instances

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading