Docs
useAsyncStatus

Track the status of an asynchronous operation with useAsyncStatus.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-async-status

Usage

"use client"
 
import { useAsyncStatus } from "@/hooks/use-async-status"
 
export function Component(props: {
  fetchData: () => Promise<{ data: string } | { error: string }>
}) {
  const [trigger, status, data] = useAsyncStatus(props.fetchData, {
    loading: <span>Loading...</span>,
    success: (data) => <span>Data: {data}</span>,
    error: (error) => <span>Error: {error}</span>,
  })
 
  return (
    <div>
      {data}
      <button onClick={trigger} disabled={status.state === "loading"}>
        {status.state === "loading" ? "Processing..." : "Click me"}
      </button>
    </div>
  )
}

Key Points

  1. asyncFn:

    • The asynchronous function to track. It can either return { data: TData } or { error: TError }.
    • If the function throws an error, it will be caught and treated as an error state.
  2. options:

    • Optional custom JSX for loading, success, and error states.
    • If not provided, data will default to null.
  3. trigger:

    • A function to manually trigger the async operation.
    • Accepts the same arguments as asyncFn.
  4. status:

    • Represents the current state of the async operation.
    • Can be idle, loading, success, or error.
  5. data:

    • Automatically renders the appropriate JSX based on the current status.
    • Uses the options if provided, otherwise falls back to null.

Type Definitions

AsyncFunction

type AsyncFunction<TArgs extends unknown[], TData, TError> = (
  ...args: TArgs
) => Promise<{ data: TData } | { error: TError }>

AsyncStatus

type AsyncStatus<TData, TError> =
  | { state: "idle" }
  | { state: "loading" }
  | { state: "success"; data: TData }
  | { state: "error"; error: TError }

FeedbackOptions

type options<TData, TError> = {
  loading?: React.ReactNode
  success?: (data: TData) => React.ReactNode
  error?: (error: TError) => React.ReactNode
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
asyncFnAsyncFunction<TArgs, TData, TError>The asynchronous function to track. It can return { data: TData } or { error: TError }.-No
options{ loading: React.ReactNode, success: (data: TData) => React.ReactNode, error: (error: TError) => React.ReactNode }Custom JSX to render for loading, success, and error states.{ loading: null }Yes

Return Values

NameTypeDescription
trigger(...args: TArgs) => Promise<void>A function to trigger the async operation. Accepts the same arguments as asyncFn.
status{ state: 'idle' } | { state: 'loading' } | { state: 'success', data: TData } | { state: 'error', error: TError }The current status of the async operation. Includes state and optional data or error.
dataReact.ReactNode | nullThe JSX to render based on the current status. Uses options if provided, otherwise defaults to null.