2
votes

getContext and setContext functions can only be called during component initialization. Is there some way to update the context value during runtime, on a click event for instance. Imagine we store a theme or a localization in a context value and want to create a button to change that. Is it possible somehow? I've tried set the context using a variable and updating that variable, but it didn't work. Like this:

//App.svelte
<script>
    import {setContext} from 'svelte';
    import Name from './components/Name.svelte';
    let name = 'John';
    setContext('name',name);
    function changeName(){
        /// how to update context here ?
        name = 'Mike'; // Doesn't work!!!
        // setContext('name',name);// Doesn't work - Errors
    }
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
    import {getContext} from 'svelte';
    let name = getContext('name');
</script>

<h1> My name is: {name}</h1>
1

1 Answers

5
votes

Use a store:

//App.svelte
<script>
    import {setContext} from 'svelte';
    import {writable} from 'svelte/store';
    import Name from './components/Name.svelte';

    let name = writable('John');
    setContext('name',name);

    function changeName(){
        $name = 'Mike';
    }
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
    import {getContext} from 'svelte';
    let name = getContext('name');
</script>

<h1> My name is: {$name}</h1>

Demo: https://svelte.dev/repl/432d3449cd9b4e5d99a303fa143b3dbc?version=3.6.7