From 1a9d37061ddb50cdb3a876b3a4772ef960a959dc Mon Sep 17 00:00:00 2001 From: daishi Date: Wed, 15 Jan 2025 10:58:59 +0900 Subject: [PATCH] fix with cached promise --- tests/react/vanilla-utils/atomWithStorage.test.tsx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/react/vanilla-utils/atomWithStorage.test.tsx b/tests/react/vanilla-utils/atomWithStorage.test.tsx index 0d515da158..77779ee80f 100644 --- a/tests/react/vanilla-utils/atomWithStorage.test.tsx +++ b/tests/react/vanilla-utils/atomWithStorage.test.tsx @@ -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] + | 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))