Psionman
Psionman

Reputation: 3699

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

<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)

Upvotes: 0

Views: 615

Answers (1)

Tristan F.-R.
Tristan F.-R.

Reputation: 4214

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

Upvotes: 1

Related Questions