Search code examples
sveltesvelte-3

Svelte UI not updated despite data change


I am trying to have button toggle a drawer component to open/close.

I have a simplified example in this REPL

I am currently using a module context that exports a function so the the parent of both components can call it. The function is called, data is updated, but the UI won't react to this.

What am I (not) doing wrong? 🧐


Solution

  • If you drop the context="module" part you can export the function as a variable and use bind:toggleSomeComp on the parent.

    Example:

    <!-- SomeComp.svelte -->
    <script>
        let isOpen = false;
        export const toggleSomeComp = () => {
            isOpen = !isOpen;
            console.log('toggle called, isOpen now = ', isOpen);
        }
    </script>
    
    <hr/>
    someComp isOpen? -> {isOpen}
    
    <!-- App.svelte -->
    <script>
        import Button from './Button.svelte';
        import SomeComp from './SomeComp.svelte';
        let name = 'world';
        let toggleSomeComp;
    </script>
    
    <h1>Hello {name}!</h1>
    
    <Button on:clicked={() => toggleSomeComp()}>
        Button is sibling of SomeComp
    </Button>
    
    <SomeComp bind:toggleSomeComp></SomeComp>