Created
February 15, 2022 21:52
-
-
Save tyler-boyd/d397902459ccf9a1b1facb98786b992a to your computer and use it in GitHub Desktop.
Svelte stores in Stencil
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
import { createStore } from '@stencil/store'; | |
export type Dispatch<T> = (value: T) => void; | |
export type Updater<T> = (value: T) => T; | |
export type Mutater<T> = (value: T) => void; | |
export interface Readable<T> { | |
subscribe: (subscription: Dispatch<T>) => void; | |
get: T; // fancy observer shit | |
} | |
export interface Writable<T> extends Readable<T> { | |
set: Dispatch<T>; | |
update: Dispatch<Updater<T>>; | |
mutate: Dispatch<Mutater<T>>; | |
} | |
export function writable<T>(initialValue: T): Writable<T> { | |
const store = createStore({ value: initialValue }); | |
const subscriptions: Dispatch<T>[] = []; | |
store.onChange('value', value => subscriptions.forEach(fn => fn(value))); | |
return { | |
subscribe(subscription) { | |
subscriptions.push(subscription); | |
}, | |
get get() { | |
return store.state.value; | |
}, | |
set(value) { | |
store.set('value', { ...value }); | |
}, | |
update(updater) { | |
this.set(updater(store.state.value)); | |
}, | |
mutate(mutater) { | |
mutater(store.state.value); | |
this.set(store.state.value); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment