How to keep the state of a component using Svelte?

572 views Asked by At

I try to keep the state "open/close" of a "Panel" component. I use the Accordion component from the library SMUI.

However, it keeps getting the default value when coming back to the page with the component.

I currently use reactive values as suggested by SvelteKit. Where am I wrong?

<script lang="ts">
    let open: boolean = false;
    $: openPanel = open;
</script>

<Panel bind:open={openPanel}>
    <Header>
        <IconButton slot="icon" toggle pressed={openPanel}>
            <Icon class="material-icons" on>expand_less</Icon>
            <Icon class="material-icons">expand_more</Icon>
        </IconButton>
    </Header>
    ...
</Panel>
1

There are 1 answers

5
brunnerh On BEST ANSWER

State is not stored anywhere by default, so if you do not take care of that yourself, it will be gone.

I commonly use a store to wrap sessionStorage for less important/persistent state such as e.g. the open/closed state of this question. SvelteKit also has a "snapshots" feature which allows storing state for a history entry, though that will only restore the state on browser back navigation or reload.

For long lived configuration, e.g. the page theme, I would use localStorage or store it in a DB on the server.