Skip to content
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

fix: should update dependents with the value of the unwrapped atom when the promise resolves #2936

Merged
merged 9 commits into from
Jan 20, 2025
10 changes: 8 additions & 2 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,11 +569,17 @@ const buildStore = (...storeArgs: StoreArgs): Store => {

const mountDependencies = (atom: AnyAtom, atomState: AtomState) => {
if (atomState.m && !isPendingPromise(atomState.v)) {
for (const a of atomState.d.keys()) {
for (const [a, n] of atomState.d) {
if (!atomState.m.d.has(a)) {
const aMounted = mountAtom(a, ensureAtomState(a))
const aState = ensureAtomState(a)
const aMounted = mountAtom(a, aState)
aMounted.t.add(atom)
atomState.m.d.add(a)
if (n !== aState.n) {
changedAtoms.set(a, aState)
aState.u?.()
invalidateDependents(aState)
}
}
}
for (const a of atomState.m.d || []) {
Expand Down
14 changes: 14 additions & 0 deletions tests/vanilla/utils/unwrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,17 @@ describe('unwrap', () => {
expect(store.get(syncAtom)).toEqual('concrete')
})
})

it('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'])
})
Loading