Last active
February 15, 2022 10:35
-
-
Save joyqi/37ec4c0cbc7b9e601a0099d6d7f71e55 to your computer and use it in GitHub Desktop.
A simple state manager
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 './store'; | |
const [store, watch] = createStore({ counter: 1 }); | |
watch((data) => { | |
console.log(data.counter); | |
}); | |
store.counter += 1; | |
store.counter += 1; |
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
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