Skip to content

Instantly share code, notes, and snippets.

@joyqi
Last active February 15, 2022 10:35
Show Gist options
  • Save joyqi/37ec4c0cbc7b9e601a0099d6d7f71e55 to your computer and use it in GitHub Desktop.
Save joyqi/37ec4c0cbc7b9e601a0099d6d7f71e55 to your computer and use it in GitHub Desktop.
A simple state manager
import {createStore} from './store';
const [store, watch] = createStore({ counter: 1 });
watch((data) => {
console.log(data.counter);
});
store.counter += 1;
store.counter += 1;
type StoreWatcher<T> = (data: T) => void;
export function createStore<T>(init: T & Record<string, any>): [T, (fn: StoreWatcher<T>, run?: boolean) => void] {
const t: T | Record<string, any> = {}, store: Record<string, any> = {};
const watcher: StoreWatcher<T>[] = [];
Object.keys(init).forEach((key: string) => {
store[key] = init[key];
Object.defineProperty(t, key, {
enumerable: true,
set: (v) => {
store[key] = v;
watcher.forEach((fn) => fn(t as T));
},
get: () => store[key]
});
});
function watch(fn: StoreWatcher<T>, run = true) {
watcher.push(fn);
if (run) {
fn(store as T);
}
}
return [t as T, watch];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment