Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active December 7, 2018 15:42
Show Gist options
  • Save itsMapleLeaf/83634a90d7a032143b04af9384e62024 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/83634a90d7a032143b04af9384e62024 to your computer and use it in GitHub Desktop.
import useSimpleState from "./useSimpleState"
type LoadingState = {
status: "idle" | "loading" | "success" | "error"
error?: string
}
export default function useLoadingState() {
const [state, setState] = useSimpleState<LoadingState>({ status: "idle" })
async function start(fn: () => Promise<void>) {
setState({ status: "loading", error: undefined })
try {
await fn()
setState({ status: "success" })
} catch (error) {
setState({
status: "error",
error: error instanceof Error ? error.message : String(error),
})
}
}
return { ...state, start }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment