Created
May 12, 2023 02:46
-
-
Save guiseek/41daf10d49792f164587afc47758f9d5 to your computer and use it in GitHub Desktop.
Stte handler
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
let state: any | |
function handleState<T = unknown>(data: T) { | |
state = data | |
// const events: ((state: T) => void)[] = [] | |
const events = new Set<(state: T | null) => void>() | |
return { | |
set(newState: T | null) { | |
if (newState === null) { | |
state = null | |
} else { | |
state = { ...state, ...newState } | |
} | |
events.forEach((cb) => cb(state)) | |
return this | |
}, | |
pick<K extends keyof T>(key: K): T[K] | null { | |
return state && state[key] ? state[key] : null | |
}, | |
get() { | |
return Object.freeze(state) | |
}, | |
on(cb: (state: T | null) => void) { | |
events.add(cb) | |
return this | |
}, | |
off(cb: (state: T | null) => void) { | |
events.delete(cb) | |
return this | |
}, | |
} | |
} | |
export const getStateHandler = <T>(data: T | null = null) => handleState(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment