diff --git a/src/vanilla/utils/unwrap.ts b/src/vanilla/utils/unwrap.ts index 2504f68d51..ab6512360f 100644 --- a/src/vanilla/utils/unwrap.ts +++ b/src/vanilla/utils/unwrap.ts @@ -44,6 +44,7 @@ export function unwrap( const promiseErrorCache = new WeakMap, unknown>() const promiseResultCache = new WeakMap, Awaited>() const refreshAtom = atom(0) + refreshAtom.debugLabel = 'refresh' if (import.meta.env?.MODE !== 'production') { refreshAtom.debugPrivate = true @@ -89,6 +90,7 @@ export function unwrap( set(refreshAtom, (c) => c + 1) }, ) + promiseAndValueAtom.debugLabel = 'promiseAndValue' // HACK to read PromiseAndValue atom before initialization promiseAndValueAtom.init = undefined @@ -96,7 +98,7 @@ export function unwrap( promiseAndValueAtom.debugPrivate = true } - return atom( + const unwrappedAtom = atom( (get) => { const state = get(promiseAndValueAtom) if ('f' in state) { @@ -108,6 +110,8 @@ export function unwrap( (_get, set, ...args) => set(anAtom as WritableAtom, ...args), ) + unwrappedAtom.debugLabel = 'unwrapped' + return unwrappedAtom }, anAtom, fallback, diff --git a/tests/vanilla/utils/unwrap.test.ts b/tests/vanilla/utils/unwrap.test.ts index be294dde54..8f3e3414fb 100644 --- a/tests/vanilla/utils/unwrap.test.ts +++ b/tests/vanilla/utils/unwrap.test.ts @@ -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', () => { @@ -150,3 +151,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']) +})