Skip to content

Instantly share code, notes, and snippets.

@danielres
Created January 2, 2024 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielres/208f10be90da3498b3df5052d7608e66 to your computer and use it in GitHub Desktop.
Save danielres/208f10be90da3498b3df5052d7608e66 to your computer and use it in GitHub Desktop.
A basic state machine using only svelte stores
<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