Leave Yamada UI a star

Star
Yamada UIYamada UIv1.6.4

useAsync

useAsync is a custom hook that executes an asynchronous function and tracks its state.

Source@yamada-ui/utils

Import

import { useAsync } from "@yamada-ui/react"
Copied!

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>
  </>
)
Copied!

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>
  </>
)
Copied!

Edit this page on GitHub

PrevioususeAnimationNextuseAsyncCallback