'How to dynamically set State using hooks
I have defined set of states using react hook useState and i need to set those state based on dynamic(responseData i.e array which is holding all errors) values.

Below pic is the response i am getting from yup library function call

Below is my code please go through the code
function SignUp(props) {
const [basicErrors, setBasicErrors] = useState({
email: false,
firstName: false,
lastName: false,
password: false,
acceptedTerms: false,
})
const [basicValues, setBasicValues] = useState({
email: null,
firstName: null,
lastName: null,
password: null,
mobile: null,
acceptedTerms: false,
})
const handleFormSubmit = (e) => {
console.log("basic-values",basicValues);
e.preventDefault()
signUpValidationSchema
.validate(
{
email: basicValues.email,
firstName: basicValues.firstName,
lastName: basicValues.lastName,
password: basicValues.password,
acceptedTerms: basicValues.acceptedTerms,
},
{ abortEarly: false }
)
.then(function(responseData) {
console.log("form validation", responseData);
})
.catch((responseData) => {
console.log(responseData.inner);
for (let i = 0; i < responseData.inner.length; i++) {
setBasicErrors({ ...basicErrors, [responseData.inner[i]['path']] : responseData.inner[i]['message']})
}
console.log("form validation error", basicErrors);
})
}
return (
);
}
Solution 1:[1]
You can use useEffect() hook for this task.
Assuming that you fetch the validation error array from backend into your React component's prop variable named validationErrors, basicErrors can be dynamically set as follows:
const [basicErrors, setBasicErrors] = useState([...]);
const validationErrors = fetchValidationErrorsAPI();
useEffect(() => {
setBasicErrors(validationErrors);
// syntax [ValidationErrors] means that
// this effect will execute everytime variable
// 'validationErrors' changes.
}, [validationErrors])
After this effect is executed, your component will re-render and basicErrors updated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
