I was trying to access a hook that i created into another function (function handleValidation) but that hook and its values were not available. When I tried to check if the function was working using a alert (example :alert(password)) I got the value for password as "undefined" …..help please
const [values, setValues] = useState({
username: "",
email: "",
password: "",
confirmPassword: "",
});
// Handling change
const handleChange = (event) => {
setValues({ values,[event.target.name]: event.target.value });
};
// Submit functionality
const handleSubmit = (event) => {
event.preventDefault();
handleValidation();
};
// Validating form
const handleValidation = () => {
const { password,confirmPassword,username, email } = values;
console.log(password)
if (password !== confirmPassword) {
console.log("Match", toast);
toast.error(
"Password and confirm password should be same.",
toastOptions
);
return false;
} else if (username === "") {
toast.error(
"Username should be greater than 3 characters.",
toastOptions
);
return false;
} else if (password.length < 8) {
toast.error(
"Password should be equal or greater than 8 characters.",
toastOptions
);
return false;
} else if (email === "") {
toast.error("Email is required.", toastOptions);
return false;
}
return true;
};
I am trying to check if the credentials entered in the form meet certain rules,
2
Answers
is this code in one function or multiple files and you gathered them ?
are they in a function or top level code ?
can you please provide more code or just post the whole page of code here
The issue in handleChange
Solution
You forgot to add spread operator before values
More Explain
For example when you type
h
in the username input using your code,handleChange
function will run and updatevalues
object, BUT not as you expected. When you console.logvalues
:and after typing one more character it will be a big mess:
and it will get worse, and that is why you could not find
password
inside thevalues
object.