GeneIT/geneit_app/src/widgets/AsyncWidget.tsx

93 lines
2.0 KiB
TypeScript
Raw Normal View History

import { Alert, Box, Button, CircularProgress } from "@mui/material";
2023-06-13 14:22:23 +00:00
import { useEffect, useRef, useState } from "react";
2023-06-13 14:16:07 +00:00
enum State {
Loading,
Ready,
Error,
}
export function AsyncWidget(p: {
loadKey: any;
load: () => Promise<void>;
errMsg: string;
build: () => React.ReactElement;
2023-06-27 17:03:39 +00:00
ready?: boolean;
errAdditionalElement?: () => React.ReactElement;
2023-06-13 14:16:07 +00:00
}): React.ReactElement {
const [state, setState] = useState(State.Loading);
const counter = useRef<any | null>(null);
const load = async () => {
try {
setState(State.Loading);
await p.load();
setState(State.Ready);
} catch (e) {
console.error(e);
setState(State.Error);
}
};
useEffect(() => {
if (counter.current === p.loadKey) return;
counter.current = p.loadKey;
load();
});
2023-07-07 16:41:00 +00:00
if (state === State.Error)
2023-06-13 14:16:07 +00:00
return (
<Box
component="div"
sx={{
2023-06-13 14:16:07 +00:00
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%",
flex: "1",
2023-07-07 16:41:00 +00:00
flexDirection: "column",
backgroundColor: (theme) =>
theme.palette.mode === "light"
? theme.palette.grey[100]
: theme.palette.grey[900],
2023-06-13 14:16:07 +00:00
}}
>
2023-07-07 16:41:00 +00:00
<Alert
variant="outlined"
severity="error"
style={{ margin: "0px 15px 15px 15px" }}
>
{p.errMsg}
</Alert>
<Button onClick={load}>Réessayer</Button>
{p.errAdditionalElement && p.errAdditionalElement()}
</Box>
2023-06-13 14:16:07 +00:00
);
2023-07-07 16:41:00 +00:00
if (state === State.Loading || p.ready === false)
2023-06-13 14:16:07 +00:00
return (
<Box
component="div"
sx={{
2023-06-13 14:16:07 +00:00
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%",
flex: "1",
backgroundColor: (theme) =>
theme.palette.mode === "light"
? theme.palette.grey[100]
: theme.palette.grey[900],
2023-06-13 14:16:07 +00:00
}}
>
2023-07-07 16:41:00 +00:00
<CircularProgress />
</Box>
2023-06-13 14:16:07 +00:00
);
2023-07-07 16:41:00 +00:00
2023-06-13 14:16:07 +00:00
return p.build();
}