diff --git a/packages/ui/src/store/store.ts b/packages/ui/src/store/store.ts index d75b23d..35251c9 100644 --- a/packages/ui/src/store/store.ts +++ b/packages/ui/src/store/store.ts @@ -2,7 +2,6 @@ export interface FavolinkStoreObserver { getState: () => T; setState: (next: SetStateAction) => void; subscribe: (listener: () => void) => () => void; - emitChange: () => void; } type SetStateFn = (prevState: T) => T; @@ -11,10 +10,11 @@ type SetStateAction = SetStateFn | T; export class FavolinkStore implements FavolinkStoreObserver { private state: T; - private listeners: (() => void)[] = []; + private listeners: Set<() => void>; constructor(initialState: T) { this.state = initialState; + this.listeners = new Set(); } getState = () => { @@ -23,29 +23,25 @@ export class FavolinkStore implements FavolinkStoreObserver { setState = (next: SetStateAction) => { const setter = next as SetStateFn; - const nextValue = typeof next === 'function' ? setter(this.state) : next; + const nextState = typeof next === 'function' ? setter(this.state) : next; - if (this.state === nextValue) { + if (this.state === nextState) { return; } - this.state = nextValue; - this.emitChange(); + this.state = nextState; + this.listeners.forEach((listener) => { + listener(); + }); }; subscribe = (listener: () => void) => { - this.listeners = [...this.listeners, listener]; + this.listeners.add(listener); return () => { - this.listeners = this.listeners.filter((l) => l !== listener); + this.listeners.delete(listener); }; }; - - emitChange = () => { - this.listeners.forEach((listener) => { - listener(); - }); - }; } export function createFavolinkStore(initialState: T) {