|
| 1 | +import axios from 'axios'; |
| 2 | +import { useContext, useState } from 'react'; |
| 3 | +import { useForm } from 'react-hook-form'; |
| 4 | +import toast from 'react-hot-toast'; |
| 5 | +import { IChangePasswordDto } from 'shared-types'; |
| 6 | +import { UserContext } from '../../context/UserContext'; |
| 7 | +import { Utils } from '../../utils/utils'; |
| 8 | +import Form from '../Form/Form'; |
| 9 | +import FormField from '../Form/FormField'; |
| 10 | +import FormInput from '../Form/FormInput'; |
| 11 | +import FormSubmitButton from '../Form/FormSubmitButton'; |
| 12 | +import Alert from '../Helpers/Alert'; |
| 13 | + |
| 14 | +type Inputs = { |
| 15 | + oldPassword: string; |
| 16 | + newPassword: string; |
| 17 | + newPasswordConfirm: string; |
| 18 | +}; |
| 19 | + |
| 20 | +function UserChangePasswordForm() { |
| 21 | + const { register, handleSubmit } = useForm<Inputs>(); |
| 22 | + const [loading, setLoading] = useState(false); |
| 23 | + const [error, setError] = useState<string | null>(null); |
| 24 | + |
| 25 | + const { logout } = useContext(UserContext); |
| 26 | + |
| 27 | + function onSubmit(inputs: Inputs) { |
| 28 | + setLoading(true); |
| 29 | + setError(null); |
| 30 | + |
| 31 | + const dto: IChangePasswordDto = inputs; |
| 32 | + |
| 33 | + axios |
| 34 | + .post<void>(`/api/auth/change-password`, dto) |
| 35 | + .then(async () => { |
| 36 | + await logout(); |
| 37 | + toast.success(`Successfully changed password`); |
| 38 | + }) |
| 39 | + .catch((err) => setError(Utils.requestErrorToString(err))) |
| 40 | + .finally(() => setLoading(false)); |
| 41 | + } |
| 42 | + |
| 43 | + return ( |
| 44 | + <Form |
| 45 | + onSubmit={handleSubmit(onSubmit)} |
| 46 | + loading={loading} |
| 47 | + > |
| 48 | + {error && <Alert>{error}</Alert>} |
| 49 | + |
| 50 | + <FormField |
| 51 | + label="Current password" |
| 52 | + hint="Confirm your current password" |
| 53 | + required |
| 54 | + > |
| 55 | + <FormInput |
| 56 | + type="password" |
| 57 | + required |
| 58 | + {...register('oldPassword', { required: true })} |
| 59 | + /> |
| 60 | + </FormField> |
| 61 | + |
| 62 | + <FormField |
| 63 | + label="New password" |
| 64 | + required |
| 65 | + > |
| 66 | + <FormInput |
| 67 | + type="password" |
| 68 | + required |
| 69 | + {...register('newPassword', { required: true })} |
| 70 | + /> |
| 71 | + </FormField> |
| 72 | + |
| 73 | + <FormField |
| 74 | + label="Re-type new password" |
| 75 | + required |
| 76 | + > |
| 77 | + <FormInput |
| 78 | + type="password" |
| 79 | + required |
| 80 | + {...register('newPasswordConfirm', { required: true })} |
| 81 | + /> |
| 82 | + </FormField> |
| 83 | + |
| 84 | + <FormSubmitButton>Change password</FormSubmitButton> |
| 85 | + <span className="ms-4 text-muted">(You will be logged out)</span> |
| 86 | + </Form> |
| 87 | + ); |
| 88 | +} |
| 89 | +export default UserChangePasswordForm; |
0 commit comments