Svelte Stores are not updating value when updated from another page

I’m new to Svelte (and Web Dev as a whole), and I’m trying to change the value of a store from another page. The value of the store is shown on the first page, while there is a button to change the value from a separate page. However, when I hit the button, it does not update the value. Below is the code for each of my pages, along with the current file structure I have. It’s worth noting that the below example is an extremely simplified version of what I’m trying to achieve, but I was not even able to get this example working.

File Structure:

enter image description here

Store:

import { writable } from 'svelte/store'

export const value = writable(1);


Homepage:

<script>
    import  { value } from '../stores/Store.js';
    let number = $value;

</script>

<p> {number} </p>

Page 1:

<script>
    import  { value }  from '../../stores/Store.js';

    function increment() {
        value.update(n => n + 1);
        console.log($value)
    }
</script>

<button on:click={increment}>
    +
</button>

I’m also attaching an repl.it of the code to interact with it:
https://replit.com/@PremRana/Stores-Bugs?v=1

I feel like I must have missed something really simple, whether it be scope related or a missing part needed for stores. Any help is appreciated.

>Solution :

Stores only exist in memory (in the browser) and all their state is lost on navigation unless it is saved somewhere. There are multiple options, which one to use depends on what the data is for/how it is used.

You could e.g. send it to a server and store it in a database or save it sessionStorage or localStorage in the user’s browser. It may make sense to wrap the store’s set method to persist the data.

There should already be questions and answers about e.g. a store that saves to localStorage.

Also let number = $value; only reads the store once. If the store were to be changed on the same page number would not update. Would recommend either using $value directly (you don’t have to copy it first to use it in markup) or using a reactive statement instead:

$: number = $value;

Leave a Reply