Skip to content

Commit

Permalink
Merge pull request #1 from SamHoque/storage-loading-state
Browse files Browse the repository at this point in the history
鈾伙笍 Added a loading state to the storage hook
  • Loading branch information
SamHoque committed May 29, 2024
2 parents e38313a + 8dc340c commit c12ecaa
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 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,6 +46,7 @@ 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>) {
Expand All @@ -54,7 +56,8 @@ export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {

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

const [isLoading, setIsLoading] = useState(true)

// Use to ensure we don't set render state after unmounted
const isMounted = useRef(false)

Expand Down Expand Up @@ -95,6 +98,7 @@ export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {
[key]: (change) => {
if (isMounted.current) {
setRenderValue(change.newValue)
setIsLoading(false)
}
}
}
Expand All @@ -110,6 +114,7 @@ export function useStorage<T = any>(rawKey: RawKey, onInit?: Setter<T>) {
} else {
setRenderValue(v !== undefined ? v : onInit)
}
setIsLoading(false)
})

return () => {
Expand Down

0 comments on commit c12ecaa

Please sign in to comment.