Last active
December 7, 2018 15:42
-
-
Save itsMapleLeaf/83634a90d7a032143b04af9384e62024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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