useAsync
useAsync
is a custom hook that executes an asynchronous function and tracks its state.
Loading...
const [flg, { toggle }] = useBoolean()
const { value, error, loading } = useAsync(
async () =>
new Promise<string>((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve("Succeeded.")
} else {
reject(new Error("A pseudo random error occurred."))
}
}, 3000)
}),
[flg],
)
return (
<VStack alignItems="flex-start">
{loading ? (
<Text>Loading...</Text>
) : error ? (
<Text>Error: {error.message}</Text>
) : (
<Text>Value: {value}</Text>
)}
<Button onClick={toggle}>Update state</Button>
</VStack>
)
If you use this code, you need to add
"use client"
to the top of the file.Usage
import { useAsync } from "@yamada-ui/react"
import { useAsync } from "@/components/ui"
import { useAsync } from "@workspaces/ui"
const { value, error, loading } = useAsync(async () => {}, [])