Skip to content

feat(utils): atomWithLazy for lazily initialized primitive atoms. #2465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Apr 4, 2024
1 change: 1 addition & 0 deletions src/vanilla/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export { atomWithObservable } from './utils/atomWithObservable.ts'
export { loadable } from './utils/loadable.ts'
export { unwrap } from './utils/unwrap.ts'
export { atomWithRefresh } from './utils/atomWithRefresh.ts'
export { atomWithLazy } from './utils/atomWithLazy.ts'
11 changes: 11 additions & 0 deletions src/vanilla/utils/atomWithLazy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { atom } from '../../vanilla.ts'
import type { SetStateAction } from '../../vanilla.ts'

export function atomWithLazy<Value>(makeInitial: () => Value) {
const wrappedAtom = atom(() => atom(makeInitial()))

return atom(
(get) => get(get(wrappedAtom)),
(get, set, value: SetStateAction<Value>) => set(get(wrappedAtom), value),
)
}
41 changes: 41 additions & 0 deletions tests/vanilla/utils/atomWithLazy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect, it, vi } from 'vitest'
import { createStore } from 'jotai/vanilla'
import { atomWithLazy } from 'jotai/vanilla/utils'

it('initializes on first store get', async () => {
const storeA = createStore()
const storeB = createStore()

let externalState = 'first'
const initializer = vi.fn(() => externalState)
const anAtom = atomWithLazy(initializer)

expect(initializer).not.toHaveBeenCalled()
expect(storeA.get(anAtom)).toEqual('first')
expect(initializer).toHaveBeenCalledOnce()

externalState = 'second'

expect(storeA.get(anAtom)).toEqual('first')
expect(initializer).toHaveBeenCalledOnce()
expect(storeB.get(anAtom)).toEqual('second')
expect(initializer).toHaveBeenCalledTimes(2)
})

it('is writable', async () => {
const store = createStore()
const anAtom = atomWithLazy(() => 0)

store.set(anAtom, 123)

expect(store.get(anAtom)).toEqual(123)
})

it('should work with a set state action', async () => {
const store = createStore()
const anAtom = atomWithLazy(() => 4)

store.set(anAtom, (prev: number) => prev * prev)

expect(store.get(anAtom)).toEqual(16)
})