diff --git a/src/vanilla/store.ts b/src/vanilla/store.ts index 0f6858a018c..67a15a77564 100644 --- a/src/vanilla/store.ts +++ b/src/vanilla/store.ts @@ -165,6 +165,8 @@ const addDependency = ( // Batch // +type BatchPriority = 'H' | 'M' | 'L' + type Batch = Readonly<{ /** Atom dependents map */ D: Map> @@ -176,8 +178,6 @@ type Batch = Readonly<{ L: Set<() => void> }> -type BatchPriority = 'H' | 'M' | 'L' - const createBatch = (): Batch => ({ D: new Map(), H: new Set(), @@ -197,8 +197,8 @@ const registerBatchAtom = ( if (!batch.D.has(atom)) { batch.D.set(atom, new Set()) addBatchFunc(batch, 'H', () => { - for (const [p, f] of atomState.l || []) { - addBatchFunc(batch, p, f) + for (const [priority, listener] of atomState.l || []) { + addBatchFunc(batch, priority, listener) } for (const listener of atomState.m?.l || []) { addBatchFunc(batch, 'M', listener) @@ -250,10 +250,9 @@ const flushBatch = (batch: Batch) => { // internal & unstable type type StoreArgs = readonly [ - getAtomState: ( - atom: Atom, + getAtomState: ( atomOnInit: ReturnType, - ) => AtomState, + ) => (atom: Atom) => AtomState, atomRead: ( atom: Atom, ...params: Parameters['read']> @@ -298,9 +297,6 @@ export type INTERNAL_PrdStore = PrdStore const buildStore = ( ...[baseGetAtomState, atomRead, atomWrite, atomOnMount, atomOnInit]: StoreArgs ): Store => { - const getAtomState = (atom: Atom) => - baseGetAtomState(atom, atomOnInit(store)) - // for debugging purpose only let debugMountedAtoms: Set @@ -737,6 +733,7 @@ const buildStore = ( sub: subscribeAtom, unstable_derive, } + const getAtomState = baseGetAtomState(atomOnInit(store)) if (import.meta.env?.MODE !== 'production') { const devStore: DevStoreRev4 = { // store dev methods (these are tentative and subject to change without notice) @@ -774,19 +771,19 @@ const buildStore = ( } export const createStore = (): Store => { - const atomStateMap = new WeakMap() - const getAtomState: StoreArgs[0] = (atom, atomOnInit) => { + const atomStateMap = new WeakMap() + const getAtomState = ((atomOnInit) => (atom) => { if (import.meta.env?.MODE !== 'production' && !atom) { throw new Error('Atom is undefined or null') } - let atomState = atomStateMap.get(atom) as AtomState | undefined + let atomState = atomStateMap.get(atom) if (!atomState) { atomState = { d: new Map(), p: new Set(), n: 0 } atomStateMap.set(atom, atomState) atomOnInit(atom, atomState) } return atomState - } + }) as StoreArgs[0] return buildStore( getAtomState, (atom, ...params) => atom.read(...params),