Loading...
Please waitLoading...
Please waitpnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-async-status
"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>
)
}
asyncFn
:
{ data: TData }
or { error: TError }
.error
state.options
:
data
will default to null
.trigger
:
asyncFn
.status
:
idle
, loading
, success
, or error
.data
:
status
.options
if provided, otherwise falls back to null
.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
}
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
asyncFn | AsyncFunction<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 |
Name | Type | Description |
---|---|---|
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 . |
data | React.ReactNode | null | The JSX to render based on the current status. Uses options if provided, otherwise defaults to null . |