Gorgsenegger
Gorgsenegger

Reputation: 7856

Reactive variable declaration in Svelte doesn't update

I've got the following code (excerpt):

<script lang="ts">
    import { MyStore } from "../stores/MyStore";
    $: numberOfSelectedItems = $MyStore.items.length;
    ...
function myFunction() {
    ...
    $MyStore.items.push(selectedItem);
    ...
}
</script>

...
<p>You've selected {numberOfSelectedItems} items.</p>

The problem is that the numberOfSelectedItems isn't updated when the items array in the store is changed. The behaviour is the same when I directly try to use $MyStore.items.length within the paragraph (<p>...</p>).

When I do it like shown below it works, but I think I'm making a mistake and there should be a better way:

<script lang="ts">
    import { MyStore } from "../stores/MyStore";
    let myLength = 0;
    $: numberOfSelectedItems = myLength;
    ...

    function myFunction() {
        ...
        $MyStore.items.push(selectedItem);
        myLength = $MyStore.items.length;
        ...
    }
</script>
...
<p>You've selected {myLength} items.</p>

Upvotes: 0

Views: 1107

Answers (1)

7nik
7nik

Reputation: 106

In Svelte, the reactivity of variables and stores is triggered only by assignment. So Svelte does not consider $MyStore.items.push(selectedItem) as a change of the store.

The correct way is either

$MyStore.items = [...$MyStore.items, selectedItem];

or

$MyStore.items.push(selectedItem);
// trigger the reactivity
$MyStore.items = $MyStore.items;

Upvotes: 3

Related Questions