umami/components/pages/settings/account/PasswordEditForm.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

import { useRef } from 'react';
2023-01-06 07:56:36 +01:00
import { Form, FormRow, FormInput, FormButtons, PasswordField, Button } from 'react-basics';
2022-12-28 05:20:44 +01:00
import useApi from 'hooks/useApi';
import useUser from 'hooks/useUser';
2023-01-10 08:59:26 +01:00
export default function PasswordEditForm({ onSave, onClose }) {
const { post, useMutation } = useApi();
2023-01-10 08:59:26 +01:00
const { user } = useUser();
const { mutate, error, isLoading } = useMutation(data =>
post(`/accounts/${user.id}/change-password`, data),
);
const ref = useRef(null);
const handleSubmit = async data => {
2023-01-10 08:59:26 +01:00
mutate(data, {
onSuccess: async () => {
onSave();
},
});
};
const samePassword = value => {
2022-12-27 02:36:48 +01:00
if (value !== ref?.current?.getValues('newPassword')) {
return "Passwords don't match";
}
return true;
};
return (
2023-01-10 08:59:26 +01:00
<Form ref={ref} onSubmit={handleSubmit} error={error}>
<FormRow label="Current password">
<FormInput name="currentPassword" rules={{ required: 'Required' }}>
<PasswordField autoComplete="off" />
</FormInput>
</FormRow>
2023-01-06 07:56:36 +01:00
<FormRow label="New password">
<FormInput
name="newPassword"
rules={{
required: 'Required',
minLength: { value: 8, message: 'Minimum length 8 characters' },
}}
>
<PasswordField autoComplete="off" />
</FormInput>
2023-01-06 07:56:36 +01:00
</FormRow>
<FormRow label="Confirm password">
<FormInput
name="confirmPassword"
rules={{
required: 'Required',
minLength: { value: 8, message: 'Minimum length 8 characters' },
validate: samePassword,
}}
>
<PasswordField autoComplete="off" />
</FormInput>
</FormRow>
<FormButtons flex>
<Button type="submit" variant="primary" disabled={isLoading}>
Save
</Button>
2023-01-10 08:59:26 +01:00
<Button onClick={onClose}>Cancel</Button>
</FormButtons>
</Form>
);
}