Skip to content

Commit

Permalink
test: should update dependents with the value of the unwrapped atom w…
Browse files Browse the repository at this point in the history
…hen the promise resolves
  • Loading branch information
dmaskasky committed Jan 8, 2025
1 parent 5ff8f63 commit 31df90f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/vanilla/utils/unwrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
promiseAndValueAtom.debugPrivate = true
}

return atom(
const unwrappedAtom = atom(
(get) => {
const state = get(promiseAndValueAtom)
if ('f' in state) {
Expand All @@ -108,6 +108,7 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
(_get, set, ...args) =>
set(anAtom as WritableAtom<Value, unknown[], unknown>, ...args),
)
return unwrappedAtom
},
anAtom,
fallback,
Expand Down
15 changes: 15 additions & 0 deletions tests/vanilla/utils/unwrap.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { atom, createStore } from 'jotai/vanilla'
import type { Atom, Getter, Setter } from 'jotai/vanilla'
import { unwrap } from 'jotai/vanilla/utils'

describe('unwrap', () => {
Expand Down Expand Up @@ -150,3 +151,17 @@ describe('unwrap', () => {
expect(store.get(syncAtom)).toEqual('concrete')
})
})

it.only('should update dependents with the value of the unwrapped atom when the promise resolves', async () => {
const store = createStore()
const asyncTarget = atom(() => Promise.resolve('value'))
const target = unwrap(asyncTarget)
const results: string[] = []
const derived = atom(async (get) => {
await Promise.resolve()
results.push('effect ' + get(target))
})
store.sub(derived, () => {})
await new Promise((r) => setTimeout(r))
expect(results).toEqual(['effect undefined', 'effect value'])
})

0 comments on commit 31df90f

Please sign in to comment.