useAsync
useAsync
is a custom hook that executes an asynchronous function and tracks its state.
Import
import { useAsync } from "@yamada-ui/react"
Usage
Editable example
const [flg, { toggle }] = useBoolean() const { value, error, loading } = useAsync( async () => new Promise<string>((resolve, reject) => { console.log("deps:", JSON.stringify(flg)) setTimeout(() => { if (Math.random() > 0.5) { resolve("✌️") } else { reject(new Error("A pseudo random error occurred")) } }, 3000) }), [flg], ) return ( <> {loading ? ( <Text>Loading...</Text> ) : error ? ( <Text>Error: {error.message}</Text> ) : ( <Text>Value: {value}</Text> )} <Button mt="md" onClick={toggle}> Update state </Button> </> )
Retry Execution
Editable example
const { value, error, loading, retry } = useAsyncRetry( async () => new Promise<string>((resolve, reject) => { setTimeout(() => { if (Math.random() > 0.5) { resolve("✌️") } else { reject(new Error("A pseudo random error occurred")) } }, 3000) }), [], ) return ( <> {loading ? ( <Text>Loading...</Text> ) : error ? ( <Text>Error: {error.message}</Text> ) : ( <Text>Value: {value}</Text> )} <Button mt="md" onClick={retry}> Retry </Button> </> )
Edit this page on GitHub