Skip to content

Commit

Permalink
fix with cached promise
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Jan 15, 2025
1 parent 031cfaa commit 1a9d370
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions tests/react/vanilla-utils/atomWithStorage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -749,9 +749,17 @@ describe('with subscribe method in string storage', () => {
describe('with custom async storage', () => {
it('does not infinite loop (#2931)', async () => {
let storedValue = 0
let cachedPromise:
| [typeof storedValue, Promise<typeof storedValue>]
| null = null
const counterAtom = atomWithStorage('counter', 0, {
async getItem(_key: string, _initialValue: number) {
return await Promise.resolve(storedValue)
getItem(_key: string, _initialValue: number) {
if (cachedPromise && cachedPromise[0] === storedValue) {
return cachedPromise[1]
}
const promise = Promise.resolve(storedValue)
cachedPromise = [storedValue, promise]
return promise
},
async setItem(_key, newValue) {
storedValue = await new Promise((resolve) => resolve(newValue))
Expand Down

0 comments on commit 1a9d370

Please sign in to comment.