Skip to content

Commit

Permalink
fix(utils): make 'loadable' update immediate after resolve (#2790)
Browse files Browse the repository at this point in the history
* fix(utils): make 'loadable' update immediate after resolve

* fix comments in #2790

---------

Co-authored-by: Daishi Kato <[email protected]>
  • Loading branch information
e7h4n and dai-shi authored Nov 11, 2024
1 parent 6afbc09 commit c883763
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
21 changes: 11 additions & 10 deletions src/vanilla/utils/loadable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ export function loadable<Value>(anAtom: Atom<Value>): Atom<Loadable<Value>> {
if (cached1) {
return cached1
}
promise
.then(
(data) => {
loadableCache.set(promise, { state: 'hasData', data })
},
(error) => {
loadableCache.set(promise, { state: 'hasError', error })
},
)
.finally(setSelf)
promise.then(
(data) => {
loadableCache.set(promise, { state: 'hasData', data })
setSelf()
},
(error) => {
loadableCache.set(promise, { state: 'hasError', error })
setSelf()
},
)

const cached2 = loadableCache.get(promise)
if (cached2) {
return cached2
Expand Down
12 changes: 12 additions & 0 deletions tests/vanilla/utils/loadable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,16 @@ describe('loadable', () => {
data: 'concrete',
})
})

it('should get the latest loadable state after the promise resolves', async () => {
const store = createStore()
const asyncAtom = atom(Promise.resolve())
const loadableAtom = loadable(asyncAtom)

expect(store.get(loadableAtom)).toHaveProperty('state', 'loading')

await store.get(asyncAtom)

expect(store.get(loadableAtom)).toHaveProperty('state', 'hasData')
})
})

0 comments on commit c883763

Please sign in to comment.