Refactored forgot password form validation and connected to redux slice

This commit is contained in:
Daniel Cojocea committed 2024-07-16 12:17:18 -04:00
1 parent 1f21212072
commit 0c11473d45
3 files changed
+112 -42

No files matched your search

+35
View File
@@ -96,6 +96,21 @@ export const deleteUser = createAsyncThunk(
} }
); );
export const forgotPassword = createAsyncThunk(
"auth/forgotPassword",
async (form, thunkApi) => {
try {
const res = await axiosInstance.post("/auth/recovery/request", form);
return res.data;
} catch (error) {
if (error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
return thunkApi.rejectWithValue(error.message);
}
}
);
const handleAuthFulfilled = (state, action) => { const handleAuthFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
@@ -133,6 +148,18 @@ const handleDeleteRejected = (state, action) => {
state.success = false; state.success = false;
state.msg = action.payload ? action.payload.msg : "Failed to delete account."; state.msg = action.payload ? action.payload.msg : "Failed to delete account.";
}; };
const handleForgotPasswordFulfilled = (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
};
const handleForgotPasswordRejected = (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to send reset instructions.";
};
const authSlice = createSlice({ const authSlice = createSlice({
name: "auth", name: "auth",
@@ -178,6 +205,14 @@ const authSlice = createSlice({
}) })
.addCase(deleteUser.fulfilled, handleDeleteFulfilled) .addCase(deleteUser.fulfilled, handleDeleteFulfilled)
.addCase(deleteUser.rejected, handleDeleteRejected); .addCase(deleteUser.rejected, handleDeleteRejected);
// Forgot password thunk
builder
.addCase(forgotPassword.pending, (state) => {
state.isLoading = true;
})
.addCase(forgotPassword.fulfilled, handleForgotPasswordFulfilled)
.addCase(forgotPassword.rejected, handleForgotPasswordRejected);
}, },
}); });
+1 -2
View File
@@ -1,8 +1,7 @@
.forgot-password-page { .forgot-password-page {
width: var(--env-var-width-1);
display: flex; display: flex;
justify-content: center; justify-content: center;
min-height: var(--env-var-height-1); height: var(--env-var-height-1);
} }
.forgot-password-form { .forgot-password-form {
+76 -40
View File
@@ -2,18 +2,21 @@ import BackgroundPattern from "../../Components/BackgroundPattern/BackgroundPatt
import "./index.css"; import "./index.css";
import React from "react"; import React from "react";
import Logomark from "../../assets/Images/key-password.png"; import Logomark from "../../assets/Images/key-password.png";
import Button from "../../Components/Button";
import LeftArrow from "../../assets/Images/arrow-left.png"; import LeftArrow from "../../assets/Images/arrow-left.png";
import { useState, useEffect } from "react"; import { useState } from "react";
import { recoveryValidation } from "../../Validation/validation"; import { credentials } from "../../Validation/validation";
import axiosInstance from "../../Utils/axiosConfig";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import Field from "../../Components/Inputs/Field"; import Field from "../../Components/Inputs/Field";
import { createToast } from "../../Utils/toastUtils";
import { useDispatch, useSelector } from "react-redux";
import { forgotPassword } from "../../Features/Auth/authSlice";
import ButtonSpinner from "../../Components/ButtonSpinner";
const ForgotPassword = () => { const ForgotPassword = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch();
const [isLoading, setIsLoading] = useState(false); // Used to disable the button while loading so user doesn't submit multiple times const { isLoading } = useSelector((state) => state.auth);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [form, setForm] = useState({ const [form, setForm] = useState({
email: "", email: "",
@@ -23,40 +26,73 @@ const ForgotPassword = () => {
"forgot-password-email-input": "email", "forgot-password-email-input": "email",
}; };
useEffect(() => { const handleSubmit = async (event) => {
const { error } = recoveryValidation.validate(form); event.preventDefault();
if (error === undefined) {
setErrors({}); const { error } = credentials.validate(form, { abortEarly: false });
if (error) {
// validation errors
const err =
error.details && error.details.length > 0
? error.details[0].message
: "Error validating data.";
setErrors(err);
createToast({
variant: "info",
body: err,
hasIcon: false,
});
} else { } else {
const validationErrors = error.details.reduce((acc, err) => { const action = await dispatch(forgotPassword(form));
return { ...acc, [err.path[0]]: err.message }; if (action.payload.success) {
}, {}); navigate("/check-email");
setErrors(validationErrors); createToast({
} variant: "info",
}, [form]); body: `Instructions sent to ${form.email}.`,
hasIcon: false,
const handleInput = (e) => { });
const fieldName = idMap[e.target.id]; } else {
setForm({ ...form, [fieldName]: e.target.value }); if (action.payload) {
}; // dispatch errors
createToast({
const handleSubmit = async () => { variant: "info",
//TODO show loading spinner body: action.payload.msg,
setIsLoading(true); hasIcon: false,
try { });
const { error } = recoveryValidation.validate(form); } else {
if (error !== undefined) { // unknown errors
throw error; createToast({
variant: "info",
body: "Unknown error.",
hasIcon: false,
});
}
} }
await axiosInstance.post(`/auth/recovery/request`, form);
navigate("/check-email");
} catch (error) {
//TODO display error (Toast?)
alert(error);
} finally {
setIsLoading(false);
} }
}; };
const handleChange = (event) => {
const { value, id } = event.target;
const name = idMap[id];
setForm((prev) => ({
...prev,
[name]: value,
}));
const { error } = credentials.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const prevErrors = { ...prev };
if (error) prevErrors[name] = error.details[0].message;
else delete prevErrors[name];
return prevErrors;
});
};
return ( return (
<div className="forgot-password-page"> <div className="forgot-password-page">
<BackgroundPattern></BackgroundPattern> <BackgroundPattern></BackgroundPattern>
@@ -82,20 +118,20 @@ const ForgotPassword = () => {
label="Email" label="Email"
isRequired={true} isRequired={true}
placeholder="Enter your email" placeholder="Enter your email"
onChange={handleInput} value={form.email}
onChange={handleChange}
error={errors.email} error={errors.email}
/> />
<div className="forgot-password-v-gap-medium"></div> <div className="forgot-password-v-gap-medium"></div>
<Button <ButtonSpinner
disabled={errors.email !== undefined || isLoading === true} disabled={errors.email !== undefined}
onClick={handleSubmit} onClick={handleSubmit}
isLoading={isLoading}
level="primary" level="primary"
label="Reset password" label="Reset password"
sx={{ sx={{
width: "100%", width: "100%",
fontSize: "13px", fontSize: "13px",
fontWeight: "200",
height: "44px",
}} }}
/> />
</div> </div>