here is my part of code for signup form
import React, { useState } from "react";
import { Link } from "react-router-dom";
import useForm from "../useForm";
import validate from "../validation";
import {
isValidLength,
isContainsLowercase,
} from "../passwordValidation";
const SignupForm = () => {
My question is when I use useState to initialize values the code doesnt work but when i do destructuring individually for multiple variables the code works. why is that?
// here i am doing object destructuring
// const [validationRules, setValidationRules] = useState({
// validLength: false,
// containsLowercase: false,
});
// here i am intializing variables individually using destructuring
const [validLength, setValidLength] = useState(false);
const [containsLowercase, setContainsLowercase] = useState(false);
function handlePassword(e) {
let new_Password = e.target.value;
if (isValidLength.test(new_Password)) {
// setValidationRules({
// ...validationRules,
// validLength: true,
// });
// OR
setValidLength(true);
CodePudding user response:
I think that the error is caused because you are modifying the state instead of overwrite. Try this:
setValidLength(prevState => {...prevState, validLength: true})
This way you take the previous state value and overwrite the validLenght
atribute.
CodePudding user response:
but the thing is the code gives error when i write this
const [validationRules, setValidationRules] = useState({
validLength: false,
containsLowercase: false,
containsUppercase: false,
containsNumber: false,
containsSymbol: false,
});
function handlePassword(e) {
let new_Password = e.target.value;
console.log(new_Password);
if (isValidLength.test(new_Password)) {
setValidationRules({
...validationRules,
validLength: true,
});
} else {
setValidationRules({
...validationRules,
validLength: false,
});
}
if (isContainsLowercase.test(new_Password)) {
setValidationRules({
...validationRules,
containsLowercase: true,
});
} else {
setValidationRules({
...validationRules,
containsLowercase: false,
});
}
if (isContainsUppercase.test(new_Password)) {
setValidationRules({
...validationRules,
containsUppercase: true,
});
} else {
setValidationRules({
...validationRules,
containsUppercase: false,
});
}