Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/vanilla/internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,8 @@ type StoreHookForAtoms = {

/** StoreHooks are an experimental API. */
type StoreHooks = {
/** Listener to notify when the atom is initialized. */
readonly i?: StoreHookForAtoms
/** Listener to notify when the atom is read. */
readonly r?: StoreHookForAtoms
/** Listener to notify when the atom value is changed. */
Expand Down Expand Up @@ -380,6 +382,7 @@ const createStoreHookForAtoms = (): StoreHookForAtoms => {

function initializeStoreHooks(storeHooks: StoreHooks): Required<StoreHooks> {
type SH = { -readonly [P in keyof StoreHooks]: StoreHooks[P] }
;(storeHooks as SH).i ||= createStoreHookForAtoms()
;(storeHooks as SH).r ||= createStoreHookForAtoms()
;(storeHooks as SH).c ||= createStoreHookForAtoms()
;(storeHooks as SH).m ||= createStoreHookForAtoms()
Expand All @@ -401,6 +404,7 @@ const atomOnMount: AtomOnMount = (_store, atom, setAtom) =>
const ensureAtomState: EnsureAtomState = (store, atom) => {
const buildingBlocks = getInternalBuildingBlocks(store)
const atomStateMap = buildingBlocks[0]
const storeHooks = buildingBlocks[6]
const atomOnInit = buildingBlocks[9]
if (import.meta.env?.MODE !== 'production' && !atom) {
throw new Error('Atom is undefined or null')
Expand All @@ -409,6 +413,7 @@ const ensureAtomState: EnsureAtomState = (store, atom) => {
if (!atomState) {
atomState = { d: new Map(), p: new Set(), n: 0 }
atomStateMap.set(atom, atomState)
storeHooks.i?.(atom)
atomOnInit?.(store, atom)
}
return atomState as never
Expand Down
11 changes: 11 additions & 0 deletions tests/vanilla/internals.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,17 @@ describe('store hooks', () => {
return { store, storeHooks }
}

describe('init hook (i)', () => {
it('should call init hook when atom state is initialized', () => {
const { store, storeHooks } = createStoreWithHooks()
const baseAtom = atom(0)
const initCallback = vi.fn()
storeHooks.i.add(baseAtom, initCallback)
store.get(baseAtom)
expect(initCallback).toHaveBeenCalledTimes(1)
})
})

describe('read hook (r)', () => {
it('should call read hook when atom is read', () => {
const { store, storeHooks } = createStoreWithHooks()
Expand Down
Loading