2023-02-27 15:20:49 +00:00
|
|
|
import "./AsyncButton.css";
|
2023-02-07 20:04:50 +00:00
|
|
|
import { useState } from "react";
|
2023-02-28 13:50:05 +00:00
|
|
|
import Spinner from "../Icons/Spinner";
|
2023-01-12 21:36:31 +00:00
|
|
|
|
2023-02-09 12:26:54 +00:00
|
|
|
interface AsyncButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
2023-02-27 15:24:31 +00:00
|
|
|
disabled?: boolean;
|
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-27 15:24:31 +00:00
|
|
|
if (loading || props.disabled) return;
|
2023-02-07 20:04:50 +00:00
|
|
|
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-28 13:50:05 +00:00
|
|
|
<button className="spinner-button" type="button" disabled={loading || props.disabled} {...props} onClick={handle}>
|
2023-02-27 15:53:44 +00:00
|
|
|
<span style={{ visibility: loading ? "hidden" : "visible" }}>{props.children}</span>
|
2023-02-28 13:50:05 +00:00
|
|
|
{loading && (
|
|
|
|
<span className="spinner-wrapper">
|
|
|
|
<Spinner />
|
|
|
|
</span>
|
|
|
|
)}
|
2023-02-07 20:04:50 +00:00
|
|
|
</button>
|
|
|
|
);
|
|
|
|
}
|