Search code examples
sveltesvelte-3svelte-component

Exported boolean not reactive?


This has always worked for me but for some reason isn't working now, and feel like I'm just missing something plainly obvious.

I have two files, one connected to a WebSocket, it exports a boolean connected initially set to false, which is set to true once the connection is established. The other file is importing the boolean, using it in its view.

However, when the WebSocket connects, the value in the view is not updated. If I switch pages and return, the correct true value is shown, but not on the initial load of the page (eg. the page was loaded before the connect happens).

A basic example of the issue is here: https://svelte.dev/repl/6b6eee6181fb4f848f98c7f261558bb6?version=3.51.0

App.svelte

<script>
    import { connected } from "./lib.svelte";
</script>

<h1>
    Connection status [{connected}]
</h1>

lib.svelte

<script context="module">
export let connected = false;

setTimeout(() => {
  connected = true;
  console.log('fired ' + connected);
}, 4000)
</script>

Solution

  • You need to use a store or pass values though props if they are not declared locally and you want them to be reactive. This has never been any different to my knowledge.

    In general, when importing from a script, use a store.