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:
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.