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

How to update data store field in Svelte

I have a data store and I update the value when a button is pressed. The value on the page ( labelled ‘data_sto’) does not get updated. What do I need to do?

REPL

App.svelte

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

<script>
  import Child, { update_sum } from './Child.svelte';
  import { board } from './data_store';
    
    let my_sum = 0
    
    function refresh() {
        my_sum = update_sum();
        console.log('after update', $board);
    }
</script>

<h1>Test imports</h1>
<button on:click={refresh}>Click</button>
<div>
    data_sto {$board.sum}
</div>
<div>
    my_sum {my_sum}
</div>
<Child />

Child.svelte

Child text

<script context="module">
    import { get } from 'svelte/store';
  import { board } from './data_store';
    
    export function update_sum() {
        let board_data = get(board);
        board_data.sum = 12;
        return board_data.sum;
}
</script>

data_store.js

import { writable } from 'svelte/store';

let board_store = {
    sum: 1,
};
export let board = writable(board_store);

(This functionality is represents the essential elements extracted from a larger Svelte project)

>Solution :

You need to call .set on your board store to update the store. The reason why your current code doesn’t work is that it’s retrieving the data with get, board_data no longer becomes reactive and rather it is just a regular JSON object

Child text

<script context="module">
    import { get } from 'svelte/store';
    import { board } from './data_store';
    
    export function update_sum() {
        let board_data = get(board);
        board_data.sum = 12;
        board.set(board_data) // to update the store
        return board_data.sum;
    }
</script>

REPL

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