pagamio-frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
64 lines (63 loc) • 1.99 kB
JavaScript
import { useState } from 'react';
import { useAuth } from '../../context';
const useChangeUserPassword = ({ onSuccess, onError, handleUpdatePassword }) => {
const { logout } = useAuth();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [showTextFieldError, setShowTextFieldError] = useState(false);
const [passwordMatchError, setPasswordMatchError] = useState(null);
const [confirmationPassword, setConfirmationPassword] = useState('');
const handleResetFields = () => {
setOldPassword('');
setNewPassword('');
setConfirmationPassword('');
};
const handleSubmit = async (e) => {
e.preventDefault();
setError(null);
setPasswordMatchError(null);
setShowTextFieldError(false);
if (newPassword !== confirmationPassword) {
setShowTextFieldError(true);
setPasswordMatchError('New password and confirm password do not match.');
return;
}
const postData = {
oldPassword,
newPassword,
confirmationPassword,
};
setIsLoading(true);
try {
await handleUpdatePassword(postData);
handleResetFields();
onSuccess();
logout();
}
catch (error) {
onError(error);
setError(error.message);
}
finally {
setIsLoading(false);
}
};
return {
form: {
passwordMatchError,
showTextFieldError,
oldPassword,
newPassword,
confirmationPassword,
setOldPassword,
setNewPassword,
setConfirmationPassword,
},
isLoading,
error,
handleSubmit,
};
};
export default useChangeUserPassword;