Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I set all the key of an object state to empty array and change just one of them in React js

I’m creating sign up form with next js and I’m handling errors with joi.js, After Fetching the data if there is error, I want if the error is in the name input I will pass it as value of the name key in the errors state and pass an empty string to the other keys (email and password), and same thing for other errors, I tried to do it but when there is no error , the keys in the errors state have always the past values.

(Sorry for my bad English)

My Sign up form and console

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

File where I fetch data Login.tsx

export default function Login() {
  const [data, setData] = useState({ name: "", email: "", password: "" });
  const [errors, setErrors] = useState({
    name: "",
    email: "",
    password: "",
  });

  const handleChange = (e) => {
    setData({
      ...data,
      [e.target.name]: e.target.value,
    });
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await fetch("/api/users", {
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
      method: "POST",
    }, { cache: 'no-store' });
    const content = await res.json();
    if(content.error) {
      setErrors({...errors, [content.error[0].path[0]]:content.error[0].message})
    }
    console.log(errors);
    
  };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

>Solution :

There will always be the old values in the errors state variable since you’re setting the new error by spreading the old ones first:
setErrors({...errors, *****})

What does your content.error contain? I can see you’re only accessing the first element (content.error[0]), but do you receive all errors for that submission? If you do, you don’t need to spread the old errors, just run through all of the reported errors from the response and recreate your errors object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading