umami/components/forms/WebsiteEditForm.js

75 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-07 11:27:12 +02:00
import React, { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { post } from 'lib/web';
2020-08-08 05:36:57 +02:00
import Button from 'components/common/Button';
2020-08-07 11:27:12 +02:00
import FormLayout, {
FormButtons,
FormError,
FormMessage,
FormRow,
} from 'components/layout/FormLayout';
2020-08-09 08:48:43 +02:00
const initialValues = {
name: '',
domain: '',
};
2020-08-07 11:27:12 +02:00
const validate = ({ name, domain }) => {
const errors = {};
if (!name) {
errors.name = 'Required';
}
if (!domain) {
errors.domain = 'Required';
}
return errors;
};
2020-08-08 05:36:57 +02:00
export default function WebsiteEditForm({ values, onSave, onClose }) {
2020-08-07 11:27:12 +02:00
const [message, setMessage] = useState();
const handleSubmit = async values => {
const response = await post(`/api/website`, values);
2020-08-09 11:03:37 +02:00
if (typeof response !== 'string') {
2020-08-07 11:27:12 +02:00
onSave();
} else {
2020-08-09 11:03:37 +02:00
setMessage('Something went wrong');
2020-08-07 11:27:12 +02:00
}
};
return (
<FormLayout>
2020-08-09 08:48:43 +02:00
<Formik
initialValues={{ ...initialValues, ...values }}
validate={validate}
onSubmit={handleSubmit}
>
2020-08-07 11:27:12 +02:00
{() => (
<Form>
<FormRow>
<label htmlFor="name">Name</label>
<Field name="name" type="text" />
<FormError name="name" />
</FormRow>
<FormRow>
<label htmlFor="domain">Domain</label>
<Field name="domain" type="text" />
<FormError name="domain" />
</FormRow>
<FormButtons>
<Button type="submit" variant="action">
Save
</Button>
2020-08-07 11:27:12 +02:00
<Button onClick={onClose}>Cancel</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}