Skip to content

Commit 8497256

Browse files
committed
add storeHooks.i to be called when atomState is created
1 parent 4661064 commit 8497256

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/vanilla/internals.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,8 @@ type StoreHookForAtoms = {
330330

331331
/** StoreHooks are an experimental API. */
332332
type StoreHooks = {
333+
/** Listener to notify when the atom is initialized. */
334+
readonly i?: StoreHookForAtoms
333335
/** Listener to notify when the atom is read. */
334336
readonly r?: StoreHookForAtoms
335337
/** Listener to notify when the atom value is changed. */
@@ -380,6 +382,7 @@ const createStoreHookForAtoms = (): StoreHookForAtoms => {
380382

381383
function initializeStoreHooks(storeHooks: StoreHooks): Required<StoreHooks> {
382384
type SH = { -readonly [P in keyof StoreHooks]: StoreHooks[P] }
385+
;(storeHooks as SH).i ||= createStoreHookForAtoms()
383386
;(storeHooks as SH).r ||= createStoreHookForAtoms()
384387
;(storeHooks as SH).c ||= createStoreHookForAtoms()
385388
;(storeHooks as SH).m ||= createStoreHookForAtoms()
@@ -401,6 +404,7 @@ const atomOnMount: AtomOnMount = (_store, atom, setAtom) =>
401404
const ensureAtomState: EnsureAtomState = (store, atom) => {
402405
const buildingBlocks = getInternalBuildingBlocks(store)
403406
const atomStateMap = buildingBlocks[0]
407+
const storeHooks = buildingBlocks[6]
404408
const atomOnInit = buildingBlocks[9]
405409
if (import.meta.env?.MODE !== 'production' && !atom) {
406410
throw new Error('Atom is undefined or null')
@@ -409,6 +413,7 @@ const ensureAtomState: EnsureAtomState = (store, atom) => {
409413
if (!atomState) {
410414
atomState = { d: new Map(), p: new Set(), n: 0 }
411415
atomStateMap.set(atom, atomState)
416+
storeHooks.i?.(atom)
412417
atomOnInit?.(store, atom)
413418
}
414419
return atomState as never

tests/vanilla/internals.test.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,17 @@ describe('store hooks', () => {
106106
return { store, storeHooks }
107107
}
108108

109+
describe('init hook (i)', () => {
110+
it('should call init hook when atom state is initialized', () => {
111+
const { store, storeHooks } = createStoreWithHooks()
112+
const baseAtom = atom(0)
113+
const initCallback = vi.fn()
114+
storeHooks.i.add(baseAtom, initCallback)
115+
store.get(baseAtom)
116+
expect(initCallback).toHaveBeenCalledTimes(1)
117+
})
118+
})
119+
109120
describe('read hook (r)', () => {
110121
it('should call read hook when atom is read', () => {
111122
const { store, storeHooks } = createStoreWithHooks()

0 commit comments

Comments
 (0)