Search code examples
javascriptreactive-programmingsvelte

Does svelte have built-in protection against updating a reactive variable in async operation when the component is unmounted


I have my App component set up like this. Only relevant code is shown for brevity.

// script
let view = 'products';

// markup
<sidebar/>
<view-container>
   {#if view === 'products'}
     <products />
   {:else if view === 'orders'}
     <orders />
   {/if}
<view-container>

In the products.svelte I have an api that fetches some data and assigns it a reactive variable.

//script
let data = [];
fetch(url).then(res => res.json()).then(json => {
  data = json; // just assume json is an array;
})

//markup
{#each data as entry (entry.id)}
  <product-card product_info={entry} />
{/each}

Given that I can switch between products and orders view with the sidebar really quickly. What will happen is the fetch call will be a bit late and the assignment to data variable will be after the products component has been destroyed. Is this cleanly handled by the library itself. Are those assignments just no-ops are real errors. If we consider an analogous scenario in react by setting state after the component there is an error.

I am aware of onMount and onDestroy hooks in svelte. I am very curious about this scenario. I can't find my answer about this from the docs.


Solution

  • The way changes to components work is:

    • The component stores which values of its state have been changed
    • It is marked as dirty and an update is scheduled
    • When the update runs, all dirty components with a DOM "fragment" get their DOM updated

    Destroying a component nulls out its fragment, hence simply nothing happens on update.