snort/packages/app/src/Element/AsyncButton.tsx

40 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-02-27 15:20:49 +00:00
import "./AsyncButton.css";
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> {
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) {
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 || props.disabled) 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-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>
)}
</button>
);
}