snort/src/Element/AsyncButton.tsx

32 lines
611 B
TypeScript
Raw Normal View History

import { useState } from "react";
2023-01-12 21:36:31 +00:00
export default function AsyncButton(props: any) {
const [loading, setLoading] = useState<boolean>(false);
2023-01-12 21:36:31 +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
}
}
} finally {
setLoading(false);
2023-01-12 21:36:31 +00:00
}
}
2023-01-12 21:36:31 +00:00
return (
<button
type="button"
disabled={loading}
{...props}
onClick={(e) => handle(e)}
>
{props.children}
</button>
);
}