V
V
vladislav31012021-03-28 20:54:38
React
vladislav3101, 2021-03-28 20:54:38

The useState function returns the old value, how can I fix it?

const SignUpContainer = () => {
  const [values, setValues] = useState({
    email: '',
    login: '',
    password: '',
    password2: '',
  });

  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setErrors(validateSignUp(values));
    if (Object.keys(errors).length === 0) {
      console.log('Ошибок нет');
    } else {
      console.log('Ошибки есть');
    }
  };

  return (
    <FormSignUp
      handleChange={handleChange}
      handleSubmit={handleSubmit}
      values={values}
      errors={errors}
    />
  );
};

export default SignUpContainer;

The validateSignUp function returns an error object, when I submit the form the state errors returns the old one. When submitting the form for the 2nd time, the new state arrives. How can the problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vladislav3101, 2021-03-28
@vladislav3101

const SignUpContainer = () => {
  const [values, setValues] = useState({
    email: '',
    login: '',
    password: '',
    password2: '',
  });

  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };

   const isValid = () => {
    const errors = validateSignUp(values);
    if (Object.keys(errors).length > 0) {
      setErrors(errors);
      return false;
    }
    return true;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (isValid()) {
      setErrors({});
      console.log('Ошибок нет');
    } else {
      console.log('Ошибки есть');
    }
  };

  return (
    <FormSignUp
      handleChange={handleChange}
      handleSubmit={handleSubmit}
      values={values}
      errors={errors}
    />
  );
};

export default SignUpContainer;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question