最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Svelte store function update - Stack Overflow

programmeradmin3浏览0评论

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: /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.

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.

Share Improve this question edited Jul 22, 2022 at 16:42 Paolo 21.1k21 gold badges76 silver badges121 bronze badges asked Nov 16, 2020 at 16:50 BaartBaart 5821 gold badge6 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

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 ments. I hope it will help you better understand how things e 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 ponent 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 ponent 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 pute 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])

if I understood your question correctly, you want to be able to change the function (logic) that is executed by getData() and you want on each function change the html to be updated

for this use case you'll need to create your own custom store

as follows in store.js

import { writable } from 'svelte/store';
// an object to hold our functions
const functions = {
        "funcA": () => {
            // do something
            return "whatevedata for a"
        },
        "funcB": () => {
            // do something
            return "the data of b"
        }
    }

// this how to create a custom store, taken from svelte documentation
function createCustomStore(defaultValue) {
    const { subscribe, set, update } = writable(defaultValue);
    return {
        subscribe,
        //custom function change func where suppliedValue the value you input to the store
        // set() is a default function for a store to change it's value
        changeFunc: (suppliedValue) => set(functions[suppliedValue]),
        reset: () => set(defaultValue)
    };
}

export const getData = createCustomStore(() => "default");


export const updateKey = () => {
        // this to update which function the store uses
        getData.changeFunc("funcB")
}

in App.svelte

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

</script>

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

we added the $ to getData because it's a store that holds reference to functions and the () is there to execute any function referenced by getData store. since it is a store on each value change (function change) of getData, the html will be updated

here is a repl of the implementation

发布评论

评论列表(0)

  1. 暂无评论