How to dynamically set State using hooks

Viewed 67

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. enter image description here

Below pic is the response i am getting from yup library function call enter image description here

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 (
    
    );
}
1 Answers

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.

Related