import React, { useState, useCallback } from 'react'; import { Button, Message, Form, Input } from 'UI'; import styles from './profileSettings.module.css'; import { toast } from 'react-toastify'; import { validatePassword } from 'App/validate'; import { PASSWORD_POLICY } from 'App/constants'; import { useStore } from 'App/mstore'; import { observer } from 'mobx-react-lite'; const ERROR_DOESNT_MATCH = "Passwords don't match"; const MIN_LENGTH = 8; const ChangePassword = () => { const { userStore } = useStore(); const updatePassword = userStore.updatePassword; const passwordErrors = userStore.updatePasswordRequest.errors; const loading = userStore.updatePasswordRequest.loading; const [oldPassword, setOldPassword] = useState(''); const [newPassword, setNewPassword] = useState<{ value: string; error: boolean }>({ value: '', error: false, }); const [newPasswordRepeat, setNewPasswordRepeat] = useState<{ value: string; error: boolean }>({ value: '', error: false, }); const [show, setShow] = useState(false); const checkDoesntMatch = useCallback((newPassword: string, newPasswordRepeat: string) => { return newPasswordRepeat.length > 0 && newPasswordRepeat !== newPassword; }, []); const isSubmitDisabled = useCallback(() => { if ( newPassword.value !== newPasswordRepeat.value || newPassword.value.length < MIN_LENGTH || oldPassword.length === 0 ) { return true; } return false; }, [newPassword, newPasswordRepeat, oldPassword]); const handleSubmit = useCallback( (e: React.FormEvent) => { e.preventDefault(); if (isSubmitDisabled()) return; if (!validatePassword(newPassword.value)) { setNewPassword({ ...newPassword, error: true }); return; } updatePassword({ oldPassword, newPassword: newPassword.value, }).then((e: any) => { const success = !e || !e.errors || e.errors.length === 0; setShow(!success); if (success) { toast.success(`Successfully changed password`); setOldPassword(''); setNewPassword({ value: '', error: false }); setNewPasswordRepeat({ value: '', error: false }); } }); }, [isSubmitDisabled, oldPassword, newPassword, updatePassword] ); return show ? (
) => setOldPassword(e.target.value)} /> ) => { const newValue = e.target.value; const isValid = validatePassword(newValue); setNewPassword({ value: newValue, error: !isValid }); }} /> ) => { const newValue = e.target.value; const isValid = newValue === newPassword.value; setNewPasswordRepeat({ value: newValue, error: !isValid }); }} /> {passwordErrors.map((err, i) => ( {err} ))}
) : (
setShow(true)}>
); }; export default observer(ChangePassword);