Skip to content

Commit

Permalink
fix(utils): make 'unwrap' update immediate after resolve
Browse files Browse the repository at this point in the history
  • Loading branch information
organize committed Nov 6, 2024
1 parent 1b77710 commit ed87699
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/vanilla/utils/unwrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,15 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
if (promise !== prev?.p) {
promise
.then(
(v) => promiseResultCache.set(promise, v as Awaited<Value>),
(e) => promiseErrorCache.set(promise, e),
(v) => {
promiseResultCache.set(promise, v as Awaited<Value>)
setSelf()
},
(e) => {
promiseErrorCache.set(promise, e)
setSelf()
}
)
.finally(setSelf)
}
if (promiseErrorCache.has(promise)) {
throw promiseErrorCache.get(promise)
Expand Down
12 changes: 12 additions & 0 deletions tests/vanilla/utils/unwrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,16 @@ describe('unwrap', () => {
await new Promise((r) => setTimeout(r)) // wait for a tick
expect(store.get(unwrap(asyncAtom))).toEqual('concrete')
})

it('should get a fulfilled value after the promise resolves', async () => {
const store = createStore()
const asyncAtom = atom(Promise.resolve('concrete'))
const syncAtom = unwrap(asyncAtom)

expect(store.get(syncAtom)).toEqual(undefined)

await store.get(asyncAtom)

expect(store.get(syncAtom)).toEqual('concrete')
})
})

0 comments on commit ed87699

Please sign in to comment.