Skip to content

useAsyncAction ​

One step a dialog or form waits on: busy while it runs, and the reason on screen when it fails.

tsx
import { useAsyncAction } from '@adecore/ui';
tsx
import { Button, FormError, useAsyncAction } from '@adecore/ui';

function wait(ms: number): Promise<void> {
    return new Promise((resolve) => window.setTimeout(resolve, ms));
}

let attempts = 0;

async function publish(): Promise<void> {
    await wait(900);
    attempts += 1;

    if (attempts % 2 === 1) {
        throw new Error('The registry refused the upload: the version already exists.');
    }
}

export default function UseAsyncActionDemo() {
    const step = useAsyncAction('Publishing failed.');

    return (
        <div className="flex w-80 flex-col items-start gap-2">
            <Button variant="primary" disabled={step.busy} onClick={() => void step.run(publish)}>
                {step.busy ? 'Publishing...' : 'Publish'}
            </Button>
            {step.failure !== null && <FormError>{step.failure}</FormError>}
        </div>
    );
}

run(work) clears the last failure, sets busy, awaits the work, and returns whether it succeeded:

tsx
const step = useAsyncAction();

const save = async (): Promise<void> => {
    if (await step.run(() => api.save(draft))) {
        onClose();
    }
};

A rejection becomes failure, through messageOf. The fallback you pass the hook is the message when the rejection is not an Error.

What it returns ​

MemberType
busybooleantrue while run awaits.
failurestring | nullThe reason the last run failed.
run(work)(work: () => Promise<unknown>) => Promise<boolean>
fail(message)(message: string) => voidSets failure from a check of your own.
clear()() => void

PromptDialog runs its confirm through this hook. AsyncAction is an exported type.

Licenses and third-party notices are listed in each package.