Skip to content
Advertisement

Svelte store function update

Svelte store documentation shows String or Integer being updated, but I did not find any dynamic function in store.

I don’t understand how to make the getData function as a writable in order to notify the html of the change.

In the following sample, I would like b to be shown after the updateKey function is called.

You will find a minimal code in REPL here: https://svelte.dev/repl/3c86bd48d5b5428daee514765c926e58?version=3.29.7

And the same code here in case REPL would be down:

App.svelte:

<script>
import { getData } from './store.js';
import { updateKey } from './store.js';
setTimeout(updateKey, 1000);
</script>

<h1>{getData()}!</h1>

store.js

import {setContext} from 'svelte';
import {writable} from 'svelte/store';

var data = {
    'a': 'a',
    'b': 'b'
};

var key = 'a';

export const getData = function() {
    return data[key];
}

export const updateKey = () => {
    key = 'b';
}

The goal is to work with a dynamic function in the store.

Advertisement

Answer

Well, I think you still have a bit of confusion about how things work in Svelte… Not sure how to best answer your question, so here’s some code for what’s you’re trying to achieve, along with some comments. I hope it will help you better understand how things come together in regards to stores.

App.svelte

<script>
    import { onMount } from 'svelte'
    import { key, data, updateKey } from './store.js'

    onMount(() => {
        // it's not safe to have an unchecked timer running -- problems would
        // occur if the component is destroyed before the timeout has ellapsed,
        // that's why we're using the `onMount` lifecycle function and its
        // cleanup function here
        const timeout = setTimeout(updateKey, 1000);
        
        // this cleanup function is called when the component is destroyed
        return () => {
            clearTimeout(timeout)
        }
    })

    // this will log the value of the `key` store each time it changes, using
    // a reactive expression (a Sveltism)
    $: console.log($key)
</script>

<!--
  NOTE: we're using the $ prefix notation to access _the value_ of the store,
        and not `data`, which would be _the store itself_ (an object with
        subscribe, set, etc.)
  -->
<h1>{$data}</h1>

store.js

import { writable, derived } from 'svelte/store'

const db = {
    'a': 'a',
    'b': 'b'
}

// a writable store with initial value 'a'
export const key = writable('a')

export const updateKey = () => {
    // a writable store has a `set` method to change its value
    key.set('b')
}

// you can use a derived store to compute derived values from
// the current value of other stores
//
// here, we're getting the value from the db when the value of
// the `key` store changes
export const data = derived([key], ([$key]) => db[$key])
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement