From e22a8c6ea18226443840f47804c15f619ae00532 Mon Sep 17 00:00:00 2001 From: Nicolas Vitaterna Date: Tue, 18 Jun 2024 16:10:32 -0400 Subject: [PATCH] feat: implement isLoading state (#56) Co-authored-by: L <6723574+louisgv@users.noreply.github.com> --- src/hook.ts | 5 ++++- src/index.test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/hook.ts b/src/hook.ts index f53037c..5250b61 100644 --- a/src/hook.ts +++ b/src/hook.ts @@ -54,6 +54,8 @@ export function useStorage(rawKey: RawKey, onInit?: Setter) { const key = isObjectKey ? rawKey.key : rawKey + const [isLoading, setIsLoading] = useState(true); + // Render state const [renderValue, setRenderValue] = useState(onInit) const [isLoading, setIsLoading] = useState(true) @@ -137,7 +139,8 @@ export function useStorage(rawKey: RawKey, onInit?: Setter) { { setRenderValue, setStoreValue, - remove + remove, + isLoading } ] as const } diff --git a/src/index.test.ts b/src/index.test.ts index ed14384..bef3b46 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -231,6 +231,36 @@ describe("react hook", () => { unmount() }) + + test('isLoading is true until value is fetched', async () => { + const { getTriggers } = createStorageMock() + + const key = 'key' + const value = 'hello' + + const { result, unmount } = renderHook(() => useStorage(key)) + + expect(result.current[2].isLoading).toBe(true) + + unmount() + }) + + test('isLoading is false after value is fetched', async () => { + const { getTriggers } = createStorageMock() + + const key = 'key' + const value = 'hello' + + const { result, unmount } = renderHook(() => useStorage(key)) + + await act(async () => { + await result.current[1](value) + }) + + expect(result.current[2].isLoading).toBe(false) + + unmount() + }) }) describe("watch/unwatch", () => {