Skip to content

Commit

Permalink
feat: implement isLoading state
Browse files Browse the repository at this point in the history
  • Loading branch information
nvitaterna committed Jun 6, 2024
1 parent e38313a commit 4412c59
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export function useStorage<T = any>(
readonly setRenderValue: React.Dispatch<React.SetStateAction<T>>
readonly setStoreValue: (v: T) => Promise<null>
readonly remove: () => void
readonly isLoading: boolean
}
]
export function useStorage<T = any>(
Expand All @@ -45,13 +46,16 @@ export function useStorage<T = any>(
readonly setRenderValue: React.Dispatch<React.SetStateAction<T | undefined>>
readonly setStoreValue: (v?: T) => Promise<null>
readonly remove: () => void
readonly isLoading: boolean
}
]
export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {
const isObjectKey = typeof rawKey === "object"

const key = isObjectKey ? rawKey.key : rawKey

const [isLoading, setIsLoading] = useState(true);

// Render state
const [renderValue, setRenderValue] = useState(onInit)

Expand Down Expand Up @@ -110,6 +114,7 @@ export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {
} else {
setRenderValue(v !== undefined ? v : onInit)
}
setIsLoading(false)
})

return () => {
Expand All @@ -132,7 +137,8 @@ export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {
{
setRenderValue,
setStoreValue,
remove
remove,
isLoading
}
] as const
}
30 changes: 30 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down

0 comments on commit 4412c59

Please sign in to comment.