Skip to content

Commit f4e7433

Browse files
committed
test: should update dependents with the value of the unwrapped atom when the promise resolves
1 parent 5ff8f63 commit f4e7433

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/vanilla/utils/unwrap.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
4444
const promiseErrorCache = new WeakMap<Promise<unknown>, unknown>()
4545
const promiseResultCache = new WeakMap<Promise<unknown>, Awaited<Value>>()
4646
const refreshAtom = atom(0)
47+
refreshAtom.debugLabel = 'refresh'
4748

4849
if (import.meta.env?.MODE !== 'production') {
4950
refreshAtom.debugPrivate = true
@@ -89,14 +90,15 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
8990
set(refreshAtom, (c) => c + 1)
9091
},
9192
)
93+
promiseAndValueAtom.debugLabel = 'promiseAndValue'
9294
// HACK to read PromiseAndValue atom before initialization
9395
promiseAndValueAtom.init = undefined
9496

9597
if (import.meta.env?.MODE !== 'production') {
9698
promiseAndValueAtom.debugPrivate = true
9799
}
98100

99-
return atom(
101+
const unwrappedAtom = atom(
100102
(get) => {
101103
const state = get(promiseAndValueAtom)
102104
if ('f' in state) {
@@ -108,6 +110,8 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
108110
(_get, set, ...args) =>
109111
set(anAtom as WritableAtom<Value, unknown[], unknown>, ...args),
110112
)
113+
unwrappedAtom.debugLabel = 'unwrapped'
114+
return unwrappedAtom
111115
},
112116
anAtom,
113117
fallback,

tests/vanilla/utils/unwrap.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it } from 'vitest'
22
import { atom, createStore } from 'jotai/vanilla'
3+
import type { Atom, Getter, Setter } from 'jotai/vanilla'
34
import { unwrap } from 'jotai/vanilla/utils'
45

56
describe('unwrap', () => {
@@ -150,3 +151,17 @@ describe('unwrap', () => {
150151
expect(store.get(syncAtom)).toEqual('concrete')
151152
})
152153
})
154+
155+
it('should update dependents with the value of the unwrapped atom when the promise resolves', async () => {
156+
const store = createStore()
157+
const asyncTarget = atom(() => Promise.resolve('value'))
158+
const target = unwrap(asyncTarget)
159+
const results: string[] = []
160+
const derived = atom(async (get) => {
161+
await Promise.resolve()
162+
results.push('effect ' + get(target))
163+
})
164+
store.sub(derived, () => {})
165+
await new Promise((r) => setTimeout(r))
166+
expect(results).toEqual(['effect undefined', 'effect value'])
167+
})

0 commit comments

Comments
 (0)