From 8646d73e15287dbd609035263c058b6847027c15 Mon Sep 17 00:00:00 2001 From: AdamW Date: Fri, 1 Nov 2024 15:36:43 +0200 Subject: [PATCH] fix(utils): make 'unwrap' update immediate after resolve --- src/vanilla/utils/unwrap.ts | 11 ++++++++--- tests/vanilla/utils/unwrap.test.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/vanilla/utils/unwrap.ts b/src/vanilla/utils/unwrap.ts index 3313980171..8166b0b452 100644 --- a/src/vanilla/utils/unwrap.ts +++ b/src/vanilla/utils/unwrap.ts @@ -62,10 +62,15 @@ export function unwrap( if (promise !== prev?.p) { promise .then( - (v) => promiseResultCache.set(promise, v as Awaited), - (e) => promiseErrorCache.set(promise, e), + (v) => { + promiseResultCache.set(promise, v as Awaited) + setSelf() + }, + (e) => { + promiseErrorCache.set(promise, e) + setSelf() + } ) - .finally(setSelf) } if (promiseErrorCache.has(promise)) { throw promiseErrorCache.get(promise) diff --git a/tests/vanilla/utils/unwrap.test.ts b/tests/vanilla/utils/unwrap.test.ts index a0ca0ed8f5..be294dde54 100644 --- a/tests/vanilla/utils/unwrap.test.ts +++ b/tests/vanilla/utils/unwrap.test.ts @@ -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') + }) })