snort/src/Element/AsyncButton.tsx

33 lines
772 B
TypeScript
Raw Normal View History

import { useState } from "react";
2023-01-12 21:36:31 +00:00
2023-02-07 19:47:57 +00:00
interface AsyncButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
onClick(e: React.MouseEvent): Promise<void> | void;
children?: React.ReactNode;
}
export default function AsyncButton(props: AsyncButtonProps) {
const [loading, setLoading] = useState<boolean>(false);
2023-01-12 21:36:31 +00:00
2023-02-07 19:47:57 +00:00
async function handle(e: React.MouseEvent) {
if (loading) return;
setLoading(true);
try {
if (typeof props.onClick === "function") {
2023-02-07 19:47:57 +00:00
const f = props.onClick(e);
if (f instanceof Promise) {
await f;
2023-01-12 21:36:31 +00:00
}
}
} finally {
setLoading(false);
2023-01-12 21:36:31 +00:00
}
}
2023-01-12 21:36:31 +00:00
return (
2023-02-07 19:47:57 +00:00
<button type="button" disabled={loading} {...props} onClick={handle}>
{props.children}
</button>
);
}