Skip to content

Commit

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

* fix comments in pmndrs#2790

---------

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
  • Loading branch information
2 people authored and dmaskasky committed Nov 14, 2024
1 parent db988fe commit 61f87fc
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 61f87fc

Please # to comment.