aboutsummaryrefslogtreecommitdiff
path: root/modern/src/settings/components/EditItemView.js
diff options
context:
space:
mode:
Diffstat (limited to 'modern/src/settings/components/EditItemView.js')
-rw-r--r--modern/src/settings/components/EditItemView.js95
1 files changed, 95 insertions, 0 deletions
diff --git a/modern/src/settings/components/EditItemView.js b/modern/src/settings/components/EditItemView.js
new file mode 100644
index 00000000..90e5294a
--- /dev/null
+++ b/modern/src/settings/components/EditItemView.js
@@ -0,0 +1,95 @@
+import React from 'react';
+import { useHistory, useParams } from 'react-router-dom';
+import { makeStyles } from '@material-ui/core/styles';
+import Container from '@material-ui/core/Container';
+import Button from '@material-ui/core/Button';
+import FormControl from '@material-ui/core/FormControl';
+
+import { useEffectAsync } from '../../reactHelper';
+import OptionsLayout from './OptionsLayout';
+import { useTranslation } from '../../common/components/LocalizationProvider';
+
+const useStyles = makeStyles((theme) => ({
+ container: {
+ marginTop: theme.spacing(2),
+ },
+ buttons: {
+ display: 'flex',
+ justifyContent: 'space-evenly',
+ '& > *': {
+ flexBasis: '33%',
+ },
+ },
+}));
+
+const EditItemView = ({
+ children, endpoint, item, setItem, validate, onItemSaved,
+}) => {
+ const history = useHistory();
+ const classes = useStyles();
+ const t = useTranslation();
+
+ const { id } = useParams();
+
+ useEffectAsync(async () => {
+ if (id) {
+ const response = await fetch(`/api/${endpoint}/${id}`);
+ if (response.ok) {
+ setItem(await response.json());
+ }
+ } else {
+ setItem({});
+ }
+ }, [id]);
+
+ const handleSave = async () => {
+ let url = `/api/${endpoint}`;
+ if (id) {
+ url += `/${id}`;
+ }
+
+ const response = await fetch(url, {
+ method: !id ? 'POST' : 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(item),
+ });
+
+ if (response.ok) {
+ if (onItemSaved) {
+ onItemSaved(await response.json());
+ }
+ history.goBack();
+ }
+ };
+
+ return (
+ <OptionsLayout>
+ <Container maxWidth="xs" className={classes.container}>
+ {children}
+ <FormControl fullWidth margin="normal">
+ <div className={classes.buttons}>
+ <Button
+ type="button"
+ color="primary"
+ variant="outlined"
+ onClick={() => history.goBack()}
+ >
+ {t('sharedCancel')}
+ </Button>
+ <Button
+ type="button"
+ color="primary"
+ variant="contained"
+ onClick={handleSave}
+ disabled={!validate()}
+ >
+ {t('sharedSave')}
+ </Button>
+ </div>
+ </FormControl>
+ </Container>
+ </OptionsLayout>
+ );
+};
+
+export default EditItemView;