Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Implement loading state to know if the storage is currently loading. #54

Merged
merged 2 commits into from
Jun 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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