Created
January 2, 2024 15:15
-
-
Save danielres/208f10be90da3498b3df5052d7608e66 to your computer and use it in GitHub Desktop.
A basic state machine using only svelte stores
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { derived, readable, writable } from 'svelte/store' | |
type States = 'view' | 'edit' | |
const state = writable<States>('view') | |
const _substate = derived(state, ($state) => { | |
if ($state === 'edit') return writable<{ item?: number }>({}) | |
return readable(null) | |
}) | |
$: substate = $_substate | |
</script> | |
<button on:click={() => ($state = $state === 'view' ? 'edit' : 'view')}>Switch</button> | |
<div><b>{$state}</b></div> | |
<hr /> | |
<pre>{JSON.stringify($substate, null, 2)}</pre> | |
<hr /> | |
{#if $state === 'edit'} | |
{#each [1, 2, 3] as i} | |
<button | |
on:click={() => { | |
if ($substate) $substate.item = i | |
}} | |
> | |
{i} | |
</button> | |
{/each} | |
{/if} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment