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

Time:01-24

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

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>

CodePudding user response:

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.

  • Related