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 reactive statement not triggering, when variable updated asynchronously in another file

A reactive statement isn’t triggering how I expect, in this toy example. I’m updating a variable x in a separate file, and I’d expect this update to trigger a reactive statement in my main app, but it doesn’t. When I use the same logic inside my main app, for variable y, it does trigger the reactive statement. Why isn’t the reactivity working the same for x as for y?

TestApp.svelte:

<script>
import { x } from './test.mjs';

let y = "unset";

async function inity() {
    await new Promise(r => setTimeout(r, 100));
    console.log("inity timeout done");
    y = "set";
}
inity();

$: console.log("x:", x);
$: console.log("y:", y);

</script>

<p>Hello world</p>>

test.mjs:

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

export let x = "unset";

async function initx() {
    await new Promise(r => setTimeout(r, 100));
    console.log("initx timeout done");
    x = "set";
}

initx();

The output I see at the console:

x: unset
y: unset
initx timeout done
inity timeout done
y: set

>Solution :

Reactivity is only analyzed within Svelte files. If you update values outside you have to use stores.

The Svelte code is compiled to include the necessary logic to call $: code on change, the JS is not touched and hence will not have any of the necessary logic. Stores have a built-in mechanism for signaling changes that Svelte can work with.

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