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