Last active
February 2, 2021 17:40
-
-
Save GarrettCannon/e6e01af5a372bb9fb133ab1004bd77d1 to your computer and use it in GitHub Desktop.
Svelte Elm like state management using built in Svelte stores
This file contains 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
import { writable, Writable, get } from "svelte/store"; | |
type Dispatch<A> = (action: A) => void; | |
type CmdEff<A> = () => Promise<A | undefined>; | |
type CmdNone = "CmdNone"; | |
type Cmd<A> = CmdEff<A> | CmdNone; | |
export const cmdNone: CmdNone = "CmdNone"; | |
export type Update<S, A> = (action: A, state: S) => [S, Cmd<A>]; | |
type Store<S, A> = { | |
state: Writable<S>; | |
dispatch: Dispatch<A>; | |
}; | |
export const initStore = <S, A>( | |
init: S, | |
reducer: Update<S, A>, | |
debug?: boolean | |
): Store<S, A> => { | |
const _state = writable(init); | |
const dispatch = (action: A) => { | |
_state.update((s) => { | |
const [state, cmd] = reducer(action, s); | |
if (cmd !== "CmdNone") { | |
cmd().then((x) => { | |
if (x) { | |
dispatch(x); | |
} | |
}); | |
} | |
return state; | |
}); | |
if (debug) { | |
console.log(action, get(_state)); | |
} | |
}; | |
return { state: _state, dispatch }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic usage example