umami/components/forms/AccountEditForm.js

75 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-09 08:48:43 +02:00
import React, { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { post } from 'lib/web';
import Button from 'components/common/Button';
import FormLayout, {
FormButtons,
FormError,
FormMessage,
FormRow,
} from 'components/layout/FormLayout';
const initialValues = {
username: '',
password: '',
};
const validate = ({ username, password }) => {
const errors = {};
if (!username) {
errors.username = 'Required';
}
if (!password) {
errors.password = 'Required';
}
return errors;
};
export default function AccountEditForm({ values, onSave, onClose }) {
const [message, setMessage] = useState();
const handleSubmit = async values => {
const response = await post(`/api/account`, values);
if (response) {
onSave();
} else {
setMessage('Something went wrong.');
}
};
return (
<FormLayout>
<Formik
initialValues={{ ...initialValues, ...values }}
validate={validate}
onSubmit={handleSubmit}
>
{() => (
<Form>
<FormRow>
<label htmlFor="username">Username</label>
<Field name="username" type="text" />
<FormError name="username" />
</FormRow>
<FormRow>
<label htmlFor="password">Password</label>
<Field name="password" type="text" />
<FormError name="password" />
</FormRow>
<FormButtons>
<Button type="submit" variant="action">
Save
</Button>
<Button onClick={onClose}>Cancel</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}