From 4412c5972547eed1577c7961c055ed91074af29c Mon Sep 17 00:00:00 2001 From: Nicolas Vitaterna Date: Thu, 6 Jun 2024 19:24:58 -0400 Subject: [PATCH] feat: implement isLoading state --- src/hook.ts | 8 +++++++- src/index.test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/hook.ts b/src/hook.ts index 7911fba..7e216ea 100644 --- a/src/hook.ts +++ b/src/hook.ts @@ -34,6 +34,7 @@ export function useStorage( readonly setRenderValue: React.Dispatch> readonly setStoreValue: (v: T) => Promise readonly remove: () => void + readonly isLoading: boolean } ] export function useStorage( @@ -45,6 +46,7 @@ export function useStorage( readonly setRenderValue: React.Dispatch> readonly setStoreValue: (v?: T) => Promise readonly remove: () => void + readonly isLoading: boolean } ] export function useStorage(rawKey: RawKey, onInit?: Setter) { @@ -52,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) @@ -110,6 +114,7 @@ export function useStorage(rawKey: RawKey, onInit?: Setter) { } else { setRenderValue(v !== undefined ? v : onInit) } + setIsLoading(false) }) return () => { @@ -132,7 +137,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", () => {