Skip to content

Instantly share code, notes, and snippets.

@tyler-boyd
Created February 15, 2022 21:52
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 tyler-boyd/d397902459ccf9a1b1facb98786b992a to your computer and use it in GitHub Desktop.
Save tyler-boyd/d397902459ccf9a1b1facb98786b992a to your computer and use it in GitHub Desktop.
Svelte stores in Stencil
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