2023-02-07 20:04:50 +00:00
|
|
|
import { useState } from "react";
|
2023-01-12 21:36:31 +00:00
|
|
|
|
|
|
|
export default function AsyncButton(props: any) {
|
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 20:04:50 +00:00
|
|
|
async function handle(e: any) {
|
|
|
|
if (loading) return;
|
|
|
|
setLoading(true);
|
|
|
|
try {
|
|
|
|
if (typeof props.onClick === "function") {
|
|
|
|
let f = props.onClick(e);
|
|
|
|
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 (
|
|
|
|
<button
|
|
|
|
type="button"
|
|
|
|
disabled={loading}
|
|
|
|
{...props}
|
|
|
|
onClick={(e) => handle(e)}
|
|
|
|
>
|
|
|
|
{props.children}
|
|
|
|
</button>
|
|
|
|
);
|
|
|
|
}
|